Writing your first test
Learn to create a test class and a test method in PHPUnit.
Writing your first test
A test method checks a single behaviour. It starts with public function testAdd(): void and contains one or a few assertions. If an assertion fails, PHPUnit marks the test as failed. A good test name says what it checks: testAdd, testEmptyCart, testNegativeAgeThrows. The test prefix is required; the @test annotation also works but the prefix is more common.
@test annotation and naming
Instead of the test prefix you can use the @test annotation: write /** @test */ above the method; then PHPUnit treats it as a test even if the name does not start with test. To avoid confusion, teams usually pick one style. Most prefer the test prefix because it makes the test visible in the method name. Do not mix the two in the same class.
Exercise Write your first test
The add method of ShoppingCart adds an item. Make ShoppingCartTest extend TestCase. Write a testAddItem method: create a new ShoppingCart, add "Bread", then check count is 1 with assertEquals.
Show example solution
Write class ShoppingCartTest extends TestCase. Inside testAddItem add new ShoppingCart(), $cart->add("Bread"), $this->assertEquals(1, $cart->count()).
Example solution:
<?php
// Here we define TestCase ourselves
class TestCase {
protected function assertEquals($expected, $actual): void {
if ($expected !== $actual) {
throw new Exception("Expected $expected, got $actual");
}
}
}
class ShoppingCart {
private array $items = [];
public function add(string $item): void { $this->items[] = $item; }
public function count(): int { return count($this->items); }
}
class ShoppingCartTest extends TestCase {
public function testAddItem(): void {
$cart = new ShoppingCart();
$cart->add("Bread");
$this->assertEquals(1, $cart->count());
}
}
// Run the test
$test = new ShoppingCartTest();
$test->testAddItem();
echo "testAddItem: PASSED\n";
Test yourself
-
Write the test method name
<?php class CartTest extends TestCase { public function ____(): void { $this->assertEquals(0, 0); } }Show answer
<?php class CartTest extends TestCase { public function testEmpty(): void { $this->assertEquals(0, 0); } } -
Which is a valid test method?
- public function testAdd(): void
- public function Add(): void
- public function _testAdd(): void
- private function testAdd(): void
Show answer
public function testAdd(): void — Correct. The test prefix and public access are enough for a test method.
-
Match the naming forms
- testAdd
- Addition check
- testEmpty
- Empty case check
- @test
- Annotation
- public function
- Access modifier