Chapter 4. Unit Testing Bad Practices

Benjamin Eberlei

WHAT'S IN THIS CHAPTER?

  • The importance of test quality

  • Avoiding bad practices and test smells

The increasing importance of software quality in PHP projects in recent years has led to an increasing adoption of unit testing in software projects based on the PHP language. Writing unit tests is as complex as writing production code, but requires a completely different focus, different programming skills, and different patterns to yield a successful testing experience. This case study shows some of the common mistakes that are made when writing unit tests and shows examples of those mistakes in test suites of popular PHP frameworks.

WHY TEST QUALITY MATTERS

You might ask yourself why the quality of tests matters. Since test code is never going to production, it might seem like "second class code" that can be ugly. After all, as long as it tests that the production code is first class and working correctly, then it is acceptable, right? Wrong!

This perspective may be valid for the first few weeks or months of a project, but it comes at the cost of maintenance problems at a later time, whenever the requirements for production code change. An elaborately tested application should have at least the same number of lines in test code as in production code, if not many more. For any change in production code, the unit tests that rely explicitly and implicitly on the changed behavior need to be adjusted, because they would indicate failure otherwise. ...

Get Real-World Solutions for Developing High-Quality PHP Frameworks and Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.