Are there best practices for writing unit tests with PHPUnit in PHP?
When writing unit tests with PHPUnit in PHP, it is important to follow best practices to ensure effective testing. Some best practices include writing clear and descriptive test names, keeping tests small and focused on a single behavior, using data providers for parameterized tests, and mocking dependencies to isolate the code being tested.
class MyTest extends PHPUnit\Framework\TestCase {
public function testAddition() {
$calculator = new Calculator();
$result = $calculator->add(2, 3);
$this->assertEquals(5, $result);
}
public function testSubtraction() {
$calculator = new Calculator();
$result = $calculator->subtract(5, 3);
$this->assertEquals(2, $result);
}
/**
* @dataProvider additionDataProvider
*/
public function testAdditionWithDataProvider($a, $b, $expected) {
$calculator = new Calculator();
$result = $calculator->add($a, $b);
$this->assertEquals($expected, $result);
}
public function additionDataProvider() {
return [
[2, 3, 5],
[5, 7, 12],
[10, 5, 15],
];
}
public function testDivisionWithMock() {
$calculator = $this->getMockBuilder(Calculator::class)
->getMock();
$calculator->expects($this->once())
->method('divide')
->with(10, 2)
->willReturn(5);
$result = $calculator->divide(10, 2);
$this->assertEquals(5, $result);
}
}