PHPUnit Testing Skill
Core Patterns
Basic Test
<?php
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase
{
private Calculator $calculator;
protected function setUp(): void
{
$this->calculator = new Calculator();
}
public function testAddition(): void
{
$this->assertEquals(5, $this->calculator->add(2, 3));
}
public function testDivideByZero(): void
{
$this->expectException(\DivisionByZeroError::class);
$this->calculator->divide(10, 0);
}
public function testMultipleAssertions(): void
{
$this->assertSame(4, $this->calculator->add(2, 2));
$this->assertSame(0, $this->calculator->subtract(2, 2));
$this->assertSame(6, $this->calculator->multiply(2, 3));
}
}
Data Providers
/**
* @dataProvider additionProvider
*/
public function testAdd(int $a, int $b, int $expected): void
{
$this->assertEquals($expected, $this->calculator->add($a, $b));
}
public static function additionProvider(): array
{
return [
'positive numbers' => [2, 3, 5],
'negative numbers' => [-1, -1, -2],
'zeros' => [0, 0, 0],
'mixed' => [10, -5, 5],
];
}
Assertions
$this->assertEquals($expected, $actual);
$this->assertSame($expected, $actual); // Strict type
$this->assertNotEquals($unexpected, $actual);
$this->assertTrue($condition);
$this->assertFalse($condition);
$this->assertNull($value);
$this->assertNotNull($value);
$this->assertCount(3, $array);
$this->assertContains('item', $array);
$this->assertArrayHasKey('key', $array);
$this->assertInstanceOf(MyClass::class, $obj);
$this->assertStringContainsString('sub', $string);
$this->assertMatchesRegularExpression('/\d+/', $string);
$this->assertEmpty($collection);
$this->assertGreaterThan(5, $value);
$this->assertJsonStringEqualsJsonString($expected, $actual);
Mocking
public function testCreateUser(): void
{
$mockRepo = $this->createMock(UserRepository::class);
$mockRepo->expects($this->once())
->method('save')
->with($this->isInstanceOf(User::class))
->willReturn(new User(1, 'Alice'));
$mockEmail = $this->createMock(EmailService::class);
$mockEmail->expects($this->once())
->method('sendWelcome')
->with('alice@test.com');
$service = new UserService($mockRepo, $mockEmail);
$result = $service->createUser('alice@test.com', 'Alice');
$this->assertEquals(1, $result->getId());
}
Lifecycle
public static function setUpBeforeClass(): void { } // Once before all
protected function setUp(): void { } // Before each test
protected function tearDown(): void { } // After each test
public static function tearDownAfterClass(): void { } // Once after all
Anti-Patterns
| Bad |
Good |
Why |
assertEquals for strict |
assertSame for type+value |
Type coercion |
| No data providers |
@dataProvider |
DRY |
| Global state |
setUp()/tearDown() |
Isolation |
| No groups |
@group smoke |
Run subsets |
Setup: composer require --dev phpunit/phpunit
Run: ./vendor/bin/phpunit or ./vendor/bin/phpunit --group smoke
Config: phpunit.xml with testsuites and coverage
Deep Patterns
See reference/playbook.md for production-grade patterns:
| Section |
What You Get |
| §1 Project Setup |
composer.json, phpunit.xml with suites, coverage config, project structure |
| §2 Test Patterns |
Assertions, #[DataProvider], Generator yields, strict comparisons |
| §3 Mocking |
createMock with callbacks, Mockery spies, consecutive returns |
| §4 Test Doubles |
In-memory fakes, repository pattern, test helpers |
| §5 Faker & Fixtures |
TestDataFactory with overrides, bulk generation |
| §6 Exception Testing |
Detailed exception assertions, warning testing |
| §7 HTTP & API Testing |
Symfony WebTestCase, auth, validation, pagination |
| §8 Database Testing |
Transaction rollback, repository integration, Doctrine |
| §9 CI/CD Integration |
GitHub Actions with MySQL/Redis, coverage thresholds |
| §10 Debugging Table |
12 common problems with causes and fixes |
| §11 Best Practices |
14-item production PHP testing checklist |
1---2name: phpunit-skill3description: Generates PHPUnit tests in PHP. Covers assertions, data providers, mocking, and test doubles. Use when user mentions "PHPUnit", "TestCase", "assertEquals", "PHP test". Triggers on: "PHPUnit", "TestCase PHP", "assertEquals PHP", "PHP unit test".4license: MIT5---6
7# PHPUnit Testing Skill
8
9## Core Patterns
10
11### Basic Test
12
13```php
14<?php
15use PHPUnit\Framework\TestCase;
16
17class CalculatorTest extends TestCase
18{
19 private Calculator $calculator;
20
21 protected function setUp(): void
22 {
23 $this->calculator = new Calculator();
24 }
25
26 public function testAddition(): void
27 {
28 $this->assertEquals(5, $this->calculator->add(2, 3));
29 }
30
31 public function testDivideByZero(): void
32 {
33 $this->expectException(\DivisionByZeroError::class);
34 $this->calculator->divide(10, 0);
35 }
36
37 public function testMultipleAssertions(): void
38 {
39 $this->assertSame(4, $this->calculator->add(2, 2));
40 $this->assertSame(0, $this->calculator->subtract(2, 2));
41 $this->assertSame(6, $this->calculator->multiply(2, 3));
42 }
43}
44```
45
46### Data Providers
47
48```php
49/**
50 * @dataProvider additionProvider
51 */
52public function testAdd(int $a, int $b, int $expected): void
53{
54 $this->assertEquals($expected, $this->calculator->add($a, $b));
55}
56
57public static function additionProvider(): array
58{
59 return [
60 'positive numbers' => [2, 3, 5],
61 'negative numbers' => [-1, -1, -2],
62 'zeros' => [0, 0, 0],
63 'mixed' => [10, -5, 5],
64 ];
65}
66```
67
68### Assertions
69
70```php
71$this->assertEquals($expected, $actual);
72$this->assertSame($expected, $actual); // Strict type
73$this->assertNotEquals($unexpected, $actual);
74$this->assertTrue($condition);
75$this->assertFalse($condition);
76$this->assertNull($value);
77$this->assertNotNull($value);
78$this->assertCount(3, $array);
79$this->assertContains('item', $array);
80$this->assertArrayHasKey('key', $array);
81$this->assertInstanceOf(MyClass::class, $obj);
82$this->assertStringContainsString('sub', $string);
83$this->assertMatchesRegularExpression('/\d+/', $string);
84$this->assertEmpty($collection);
85$this->assertGreaterThan(5, $value);
86$this->assertJsonStringEqualsJsonString($expected, $actual);
87```
88
89### Mocking
90
91```php
92public function testCreateUser(): void
93{
94 $mockRepo = $this->createMock(UserRepository::class);
95 $mockRepo->expects($this->once())
96 ->method('save')
97 ->with($this->isInstanceOf(User::class))
98 ->willReturn(new User(1, 'Alice'));
99
100 $mockEmail = $this->createMock(EmailService::class);
101 $mockEmail->expects($this->once())
102 ->method('sendWelcome')
103 ->with('alice@test.com');
104
105 $service = new UserService($mockRepo, $mockEmail);
106 $result = $service->createUser('alice@test.com', 'Alice');
107
108 $this->assertEquals(1, $result->getId());
109}
110```
111
112### Lifecycle
113
114```php
115public static function setUpBeforeClass(): void { } // Once before all
116protected function setUp(): void { } // Before each test
117protected function tearDown(): void { } // After each test
118public static function tearDownAfterClass(): void { } // Once after all
119```
120
121### Anti-Patterns
122
123| Bad | Good | Why |
124|-----|------|-----|
125| `assertEquals` for strict | `assertSame` for type+value | Type coercion |
126| No data providers | `@dataProvider` | DRY |
127| Global state | `setUp()`/`tearDown()` | Isolation |
128| No groups | `@group smoke` | Run subsets |
129
130## Setup: `composer require --dev phpunit/phpunit`
131## Run: `./vendor/bin/phpunit` or `./vendor/bin/phpunit --group smoke`
132## Config: `phpunit.xml` with testsuites and coverage
133
134## Deep Patterns
135
136See `reference/playbook.md` for production-grade patterns:
137
138| Section | What You Get |
139|---------|-------------|
140| §1 Project Setup | composer.json, phpunit.xml with suites, coverage config, project structure |
141| §2 Test Patterns | Assertions, #[DataProvider], Generator yields, strict comparisons |
142| §3 Mocking | createMock with callbacks, Mockery spies, consecutive returns |
143| §4 Test Doubles | In-memory fakes, repository pattern, test helpers |
144| §5 Faker & Fixtures | TestDataFactory with overrides, bulk generation |
145| §6 Exception Testing | Detailed exception assertions, warning testing |
146| §7 HTTP & API Testing | Symfony WebTestCase, auth, validation, pagination |
147| §8 Database Testing | Transaction rollback, repository integration, Doctrine |
148| §9 CI/CD Integration | GitHub Actions with MySQL/Redis, coverage thresholds |
149| §10 Debugging Table | 12 common problems with causes and fixes |
150| §11 Best Practices | 14-item production PHP testing checklist |