DEV Community

pO0q 🦄
pO0q 🦄

Posted on • Updated on

PHP: what if your tests taste bad?

Hopefully, this post will help you understand the purpose of unit tests.

Disclaimer

The post focuses on classic errors. It's not a step-by-step tutorial.

Why run units tests?

Unit tests does not just consist of writing short functions with the PHPunit vendor to ensure there are no error or regression during maintenance.

The goal is to write testable code to be tested with the vendor and its helpers.

"Testable code" implies that your application has the right architecture for testing, which usually means you follow some fundamental principles (e.g., S.O.L.I.D.).

In such case, your app is composed of small pieces that can be tested individually (~ units), which is very different than testing huge blocks of code that handle too much responsibilities.

Is TDD the ultimate approach?

TDD means "Test Driven Development," and does not just consist of writing your tests before the actual code.

The idea is to describe a problem in details and use the test to solve it.

We won't see this approach in details here, but you may learn useful concepts by googling the term.

TDD can be beneficial, but be aware there are some requirements, and I would recommend the help of more experienced developers, especially if you're just getting started with unit tests.

5 classic errors to avoid in your tests

It's not an exhaustive list, but you may want to prevent the following situations:

  • your code coverage is low, which means entire parts of the code remain untested
  • your test does not break when you change the actual code
  • your tests always succeed, even when you use different arguments in your functions or classes
  • you're testing the keys of an array but not its values (same for objects and properties)
  • you let the AI (e.g., ChatGPT) write your tests: ensure you review its results and/or write better prompts

Wrap this up

Unit tests are great, but it requires the appropriate architecture. Code coverage is necessary but not sufficient.

Bad tests can give you the false impression of safety, but don't be intimated and practice!

Top comments (0)