Back to results for “Unit Testing with PHPUnit”
PHP › Unit Testing with PHPUnit

What is PHPUnit, and what is a unit test meant to actually verify about a piece of code?

Beginner

Answer

PHPUnit is the most widely used testing framework in the PHP ecosystem, providing the tools needed to write, organize, and run automated tests against your code, and a unit test specifically focuses on verifying that one small, isolated piece of code, typically a single function or method, behaves exactly as expected when given a specific set of inputs, checking that it produces the correct output or correctly performs the expected action, without needing to manually and repeatedly test that same logic by hand every single time a change is made.
public function testAddReturnsCorrectSum(): void
{
    $calculator = new Calculator();
    $this->assertEquals(5, $calculator->add(2, 3));
}
Real-world example A developer writes a unit test verifying that a Calculator class's add method correctly returns five when given the inputs two and three, and can now run that same test automatically at any time to instantly confirm that behavior still works correctly.

Common follow-ups: What is the difference between a unit test and an integration test?;How do you actually run PHPUnit tests from the command line?