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

Robert Basic:
PHP traits to create test doubles
Apr 04, 2017 @ 15:47:15

In a new post to his site Robert Basic shows how to make use of traits to create test doubles in your unit testing practice. He sees them as a simple method for keeping tests clean and not having mocks/fakes/etc. all over.

Keeping your application or library code well organized, easy to follow, and read is important. Your test code should not be exempt from those rules, you should follow good testing conventions.

One part of my tests that I feel like that are out of control are the test doubles. Dummies, fakes, mocks… Seems like they are everywhere and that I keep writing the same ones over and over again. I do follow some good practices on how to reduce code duplication in my tests, but these mocks… Ugh.

He starts with a simple example, showing a test that evaluates the result of a transaction being executed (true or false). However, he describes the eventual "creep" of the tests as more are added and, with each, more "transaction" object instances are required. He suggests refactoring the creation of those doubles into traits where the class they're called from can inherit them and test setup is a bit cleaner. He proposes a "trait for every double" so that they can be easily included as needed and without conflict.

tagged: traits unittest double mock tutorial example setup object

Link: https://robertbasic.com/blog/php-traits-to-create-test-doubles/


Trending Topics: