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

Matthieu Napoli:
Using anonymous classes to write simpler tests
Jan 24, 2017 @ 16:33:18

In a recent post to his site Matthieu Napoli shows you how to use the recently added anonymous classes functionality to help make your unit tests simpler. Anonymous classes allow for the on-demand creation of class instances without the need for the predefined class being required.

Anonymous classes were added to PHP 7. This article intends to show how useful they can be for writing tests.

He breaks it down into the three most useful places he uses them in his tests:

  • mocking classes to make it simpler to test method output
  • spies looking at properties in the mock class
  • fixture classes to help with needs such as reflection tests

Code examples are provided for each of the examples, especially the final point there.

tagged: anonymous class testing unittest mock spy fixture

Link: http://mnapoli.fr/anonymous-classes-in-tests/

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: