Analyze your tests with PHPStan

Jun 10, 2024·
Gert de Pagter
Gert de Pagter
· 2 min read

Hopefully you are already using PHPStan to analyze your source code. But you shouldn’t stop there, in fact, you should also make sure you are analyzing your test code.

Why analyze your tests

If you are already using PHPStan to analyze your source code, then you probably see the value in static analysis. The same reasons for analyzing your source code are true for your tests. You can find bugs without running your code, and it tells you of potential errors.

There is one difference between your test and source code however. Which is that your test code is (probably) always executed in your CI. Meaning that if an error is guaranteed to occur you would notice it while running your tests. But if you have a larger project where the tests may take a long time, the static analysis might be faster.

There are more reasons to analyze your tests though. PHPStan will also help you find assertions to make your tests more clear, and detect assertions that are always true.

Useful extensions

The best extension to use if you are analyzing your tests is the PHPstan PHPUnit extension.

This will detect that the following assertion is useless, as the value is always true. This is of course a simplified example, but I’ve seen conditions like these in my tests before.

$this->assertTrue(true);

Another great feature of the plugin is that it will tell you if you can use more specific assertions. You can read why that is usefull right here.

So for example it will tell you to make the following change:

- $this->assertSame(true, $var);
+ $this->assertTrue($var);

Conclusion

If you aren’t analyzing your tests yet, start doing so today. Simply add your tests folder to your PHPStan config and start today. You can either add all your errors to the baseline, and fix them at a later point, or perhaps fix them today.

If you want to get notified of the next blog post, join the newsletter.