PHPUnit

August 6, 2024

What is PHPUnit?

PHPUnit is a unit testing framework for PHP

As the name suggests it is for unit testing, meaning it tests parts of a codebase in isolation, rather than integration testing where the parts are combined and tested to see how they work together (though it can be used for both depending on your specific use case). PHPUnit makes it easy to write standardized PHP tests for your codebase, working hand in hand with your CI (Continuous Integration) system to ensure tests are reliable and repeatable across team members and environments.

Enabling XML Output

PHPUnit can be configured to produce JUnit XML output by adding the --log-junit argument to your command line. ex:

1phpunit --log-junit output.xml

will produce XML output in the output.xml file.

Test Suite naming

By default PHPUnit use the name of your PHP files as the name attribute of the output XML. For example, this test code

1final class EmailTest extends TestCase
2{
3 public function testCanBeCreatedFromValidEmail(): void
4 {
5 $string = 'user@example.com';
6 ...
7 }
8}

will produce XML output that looks like this:

1<testsuites>
2 <testsuite tests="2">
3 <testsuite name="Project" tests="2" time="0.000969">
4 <testsuite name="EmailTest" file=".../tests/EmailTest.php">
5 <testcase name="testCanBeCreatedFromValidEmail"
6 file="...tests/EmailTest.php"
7 line="6"
8 class="EmailTest"
9 classname="EmailTest"
10 assertions="1"
11 time="0.000803"/>
12...

Handling Retries

PHPUnit does not have a function to automatically retry failed tests, but you can customize the test failure behavior using the command line settings.

If you need to retry a lot of tests that is a strong indicator that you may have flaky tests. These are tests that sometimes pass and sometimes fail, slowing down your development process. You can get early access to Trunk’s new Flaky Tests tool to manage these types of tests better.

Other Configuration

See an example of PHPUnit invoked from a GitHub action here.

Try it yourself or
request a demo

Get started for free

Try it yourself or
Request a Demo

Free for first 5 users