PHPunit in PHP
Here is a simple example of using PHPUnit to test a basic PHP class. This example demonstrates creating a class to be tested, writing the corresponding test file, and running the test.
1. The Class to be Tested (Calculator.php)
First, define the class and method(s) you want to test. In this case, a
Calculator class with an add method. // Calculator.php
class Calculator {
public function add($a, $b) {
return $a + $b;
}
public function subtract($a, $b) {
return $a - $b;
}
}
2. The Test Case (CalculatorTest.php)
Next, create a new test class that extends
PHPUnit\\Framework\\TestCase. By convention, the test file should be named after the class it tests, with "Test" appended (e.g., CalculatorTest.php). Test methods within the class must be public and their names should typically start with
test (e.g., testAddition). Inside these methods, you use assertion methods provided by PHPUnit (like assertEquals) to verify the expected output. // CalculatorTest.php
use PHPUnit\Framework\TestCase;
final class CalculatorTest extends TestCase {
public function testAddition(): void {
// Arrange: Set up the necessary objects and inputs
$calculator = new Calculator();
$expectedResult = 5;
// Act: Call the method being tested
$actualResult = $calculator->add(2, 3);
// Assert: Verify that the actual result matches the expected result
$this->assertEquals($expectedResult, $actualResult);
}
public function testSubtraction(): void {
$calculator = new Calculator();
$this->assertEquals(2, $calculator->subtract(5, 3));
}
}
3. Running the Test
Assuming you have PHPUnit installed (typically via Composer in your project's
vendor/bin directory), you can run the tests from your terminal. # To run all tests in the current directory:
./vendor/bin/phpunit
# To run a specific test file:
./vendor/bin/phpunit CalculatorTest.php
The output will indicate whether the tests passed or failed, how many assertions were made, and the time taken.
For more assertion methods and detailed documentation, refer to the official PHPUnit Manual.