Your First Test
With PHPUnit installed, it's time to write an actual test. A PHPUnit test is just a regular PHP class with a few conventions: it extends a base class provided by PHPUnit, and its test methods follow a naming rule so PHPUnit knows which methods to run as tests.
The TestCase Base Class
Every test class extends PHPUnit\Framework\TestCase. This base class supplies all of the
assert*() methods you will use to check results, plus lifecycle hooks like setUp()
(covered on the Test Lifecycle page).
Naming Your Test Methods
By default, PHPUnit only treats a method as a test if its name starts with the word test,
for example testAddsTwoNumbers(). This is how PHPUnit tells your test methods apart from
ordinary helper methods you might add to the same class.
If you would rather name a method something more descriptive without the test prefix, you
can mark it with an @test annotation in its doc comment instead:
/**
* @test
*/
public function it_adds_two_numbers()
{
$this->assertEquals(5, (2 + 3));
}
Both styles are equally valid; the test prefix is by far the more common convention and the
one used throughout the rest of this track.
Worked Example: Testing a Calculator
Say your project has a small Calculator class in src/Calculator.php:
<?php
class Calculator
{
public function add($a, $b)
{
return $a + $b;
}
}
The matching test in tests/CalculatorTest.php looks like this:
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
public function testAddsTwoNumbers()
{
// Arrange
$calculator = new Calculator();
// Act & Assert
$this->assertEquals(5, $calculator->add(2, 3));
}
}
Running the Test
From the project root, run PHPUnit against this single file:
./vendor/bin/phpunit tests/CalculatorTest.php
A passing run prints a single green dot per passing test, followed by a summary line:
. 1 / 1 (100%)
Time: 00:00.005, Memory: 6.00 MB
OK (1 test, 1 assertion)
What a Failing Test Looks Like
Now suppose add() had a bug and returned $a - $b instead. Running the same test
command prints an F instead of a dot, followed by a diff showing what PHPUnit expected versus
what it actually got:
F 1 / 1 (100%)
There was 1 failure:
1) CalculatorTest::testAddsTwoNumbers
Failed asserting that -1 matches expected 5.
/path/to/tests/CalculatorTest.php:10
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.
The failure message always names the test method that failed, the file and line of the assertion, and the expected vs. actual values — everything you need to jump straight to the bug.
assertEquals().