Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Adam Wathan:
Replacing Mocks with Spies
Oct 13, 2016 @ 15:25:14

In this post to his site Adam Wathan shares a unit testing tip that can help you with more correct verification in your testing - replacing mocks with spies.

Mock objects are useful when verifying that a method was called is more important than verifying the outcome of calling that method.

[...] Mocks are a great tool, but it’s always bugged me that they force you to set expectations in advance instead of making assertions at the end like you would in a traditional test.

He gives a Laravel-based example of using Mockery to set an "expects" call on a method to ensure it's correctly called. He points out, however, that this method is more useful for checking the result of the method call and not really the fact that it was called (a slight but interesting difference). He then gives an example of testing the PHP function strrev and the phases you would go through in the testing process. He suggests that, in the creation of the mock object, you're mixing up the "setup" phase with the "assertion" phase and making them dependencies. He shows how, with a switch over to using spies instead, including the code updates for Mockery that change the mock object creation and split out the assertion from the creation.

tagged: mock spy unittest mockery assertion setup

Link: https://adamwathan.me/2016/10/12/replacing-mocks-with-spies/


Trending Topics: