如何为PHPUnit的预言对象提供属性?

时间:2017-04-21 11:59:51

标签: unit-testing phpunit prophecy

我正在使用Prophecy嘲笑API。

payments()的api对象的调用将返回一个具有get($id)方法的对象,该方法返回另一个具有一些方法和属性的对象。其中一个属性是ID,我想测试那是我所期望的。

如果没有嘲笑任何东西,使用实时API,这可能会起作用:

$payment = $api->payments()->get(12345);
$this->assertEquals(12345, $payment->id);

要模拟API,请将其设置为:

$mock_payment = $this->prophesize('Api\\Resources\\Payment');

$mock_payments = $this->prophesize('Api\\Services\\PaymentsService');
$mock_payments->get(12345)->willReturn($mock_payment->reveal());

$api = $this->prophesize('Api');
$api->payments()->willReturn($mock_payments->reveal());

// Now the test code from above:
$payment = $api->payments()->get(12345);
$this->assertEquals(12345, $payment->id)

但是,我无法弄清楚如何为reveal() - ed模拟付款对象提供公共ID属性,以及如何将其设置为传入的ID(12345)?

编辑:简化问题。

我有第三方API,我无法更改,也不想测试。它返回某些类对象的实例,其中的数据可通过混合的公共属性和getter获得。

SUT:

function doSomething($api) {
  $result = $api->getResult();
  return "Born: $result->born, " . $result->getAge() . " years old.";
}

我想测试一下:

function testDoSomething() {
   // ...mock the $api so that getResult() returns an object like the 
   // expected one which has a born property set to "1 April 2016" and a 
   // and a getAge method that will return "1".
   // ...
   $result = doSomething($api);
   $this->assertEquals("Born: 1 April 2016, 1 years old.");
}

1 个答案:

答案 0 :(得分:0)

我相信你忘记透露api预言。

        $mock_payment = $this->prophesize (Payment::class);

        // ---- HERE -----------------
        $mock_payment->id = 12345;
        // ---------------------------
        $mock_payment->get()->willReturn (1);

        $mock_payments = $this->prophesize (PaymentsService::class);
        $mock_payments->get (12345)->willReturn ($mock_payment->reveal ());

        $api = $this->prophesize (Api::class);
        $api->payments ()->willReturn ($mock_payments->reveal ());

        // ---- AND HERE -------------
        $api = $api->reveal();
        // ---------------------------

        $payment = $api->payments ()->get (12345);
        $this->assertEquals (12345, $payment->id);