PHP Unit Testing

🧪 PHP Unit Testing – Write Reliable Code with PHPUnit

Unit testing helps ensure that your PHP code works correctly and remains bug-free as you make changes. In this tutorial, you’ll learn how to use PHPUnit, the most popular unit testing framework for PHP. 🚀


📌 What is PHPUnit?

PHPUnit is a testing framework for PHP that helps you write automated tests for your functions and classes.

✅ Why Use PHPUnit?

  • ✔ Ensures your code works correctly.
  • ✔ Helps prevent bugs when making changes.
  • ✔ Automates testing instead of manual checking.

📥 Installing PHPUnit

You can install PHPUnit via Composer:

composer require --dev phpunit/phpunit

Verify the installation:

vendor/bin/phpunit --version

📝 Writing Your First PHPUnit Test

Let’s create a simple function and write a test for it.

📌 Function to Test

We’ll test a function that adds two numbers.

<?php
// File: src/Calculator.php
class Calculator {
    public function add($a, $b) {
        return $a + $b;
    }
}
?>

📌 Writing a Test Case

Create a test file inside the tests/ folder.

<?php
// File: tests/CalculatorTest.php
use PHPUnit\Framework\TestCase;

require_once "src/Calculator.php";

class CalculatorTest extends TestCase {
    public function testAdd() {
        $calc = new Calculator();
        $this->assertEquals(5, $calc->add(2, 3));
    }
}
?>

🚀 Running the Test

Run the test using:

vendor/bin/phpunit tests/

🔹 Common PHPUnit Assertions

PHPUnit provides several assertions to check values.

Assertion Description
assertEquals($expected, $actual) Checks if two values are equal.
assertTrue($value) Checks if a value is true.
assertFalse($value) Checks if a value is false.
assertNull($value) Checks if a value is null.

🎯 Summary

  • PHPUnit helps automate testing in PHP.
  • Use Composer to install PHPUnit.
  • Write test cases using the TestCase class.
  • Run tests with vendor/bin/phpunit.

🚀 Next Steps

Try writing more tests for your PHP code and make it bug-free! 🛠️