I would like to test a method that just call a method of my entity object and persists it to the database.
public function setNameAndPersistObject($entityObject) {
$entityObject->setName("John");
$this->entityManager->persist($entityObject);
}
Both $entityObject and $entityManager are mocks, not actual objects.
I would like to test the call order of the called methods, to test that 'persist' gets called after 'setName', so the new name "John" gets saved in the database. How would I do that in PHPUnit?
Well... Not sure if this is the best/most clean way to do this, but recently I needed to check order between methods and this worked for me: you can simply have a variable and use it by reference on those methods. For example:
$name=null;
$mock1 = $this
->getMockBuilder(Entity::class)
->setMethods(['setName'])
->getMock();
$mock1->expects($this->any())
->method('setName')
->willReturnCallback(function($value) use (&$name) {
$name = $value;
});
$mock2 = $this
->getMockBuilder(EntityManager::class)
->setMethods(['persist'])
->getMock();
$mock2->expects($this->any())
->method('persist')
->willReturnCallback(function($object) use (&$name) {
$this->assertNotNull($name);
});
This should do the trick, at least. Notice it will fail if you create more mocks using the same variable to save the name. Another option is to include in the first mock a function to return the value stored in name and call that function in the second mock. This will not be perfect but still a little bit safer.