Reputation: 21397
I'm mocking an API with Prophecy.
A call on the api object to payments()
will return an object that has a get($id)
method, which returns another object which has a few methods and properties. One of the properties is ID and I want to test that that's what I expect.
Without mocking anything, using the live API, this might work:
$payment = $api->payments()->get(12345);
$this->assertEquals(12345, $payment->id);
To mock the API I'm setting it up like:
$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)
However I can't figure out how to give the reveal()
-ed mock payment object a public ID property, and how to set that to the passed-in ID (12345
)?
I have a 3rd party API that I cannot change and do not wish to test. It returns instances of certain classes of object with data available through a mix of public properties and getters.
SUT:
function doSomething($api) {
$result = $api->getResult();
return "Born: $result->born, " . $result->getAge() . " years old.";
}
I want to test:
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.");
}
Upvotes: 2
Views: 3664
Reputation: 16035
I beleive you've forgotten to reveal the api prophecy.
$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);
Upvotes: 2