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

QaFoo Blog:
Using Traits With PHPUnit
Nov 29, 2016 @ 12:26:19

The QaFoo site has a new post showing an interesting practice that could be used in your PHPUnit tests to provide additional functionality without the need for complicated inheritance - the use of traits.

As we already wrote that "Code Reuse By Inheritance" has lots of problems and we consider it a code smell. You should always aim to use Dependency Injection, most likely Constructor Injection. But with test cases in PHPUnit we cannot do this because we have no control about how and when our test cases are created. There are a similar problem in other frameworks, like we discussed in "Object Lifecycle Control". We also blogged about traits as a Code Smell, but let me show and explain why they might be fine to use in your test cases.

They provide an example of where the use of traits might be acceptable starting with a simple test case to check the login behavior with an invalid password. This uses an "is a" inheritance relationship with a parent test class with setUp/tearDown method. This refactored a bit to make use of traits to provide common login functionality based on methods in a trait. The post wraps up talking about traits as a "code smell" despite them seemingly making the test code cleaner, mostly that it limits the ability to change functionality by simply changing the associated code.

tagged: traits phpunit tests code smell example tutorial

Link: https://qafoo.com/blog/092_using_traits_with_phpunit.html