2

我正在用Prophecy模拟一个 API 。

对 api 对象的调用payments()将返回一个具有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)?

编辑:简化问题。

我有一个无法更改且不想测试的第 3 方 API。它返回某些对象类的实例,其中包含通过公共属性和 getter 的混合可用的数据。

苏特:

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.");
}
4

1 回答 1

2

我相信你忘了透露 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);
于 2017-09-02T17:21:00.167 回答