How To Test PHP Code With PHPUnit

In this tutorial, I will let you know how to install PHPUnit pears in the system. I also create a class and define method into them. We’ll create a test case and run test cases using the command.

PEAR is a framework and distribution system for reusable PHP components. You can find PHP pears Here. PHP provides many pears like PHPUnit, GDlib, etc, here you will learn how to install and upgrade your PHP pears in Windows.

Below are sample steps to needed install the PHP unit in your system, I am assuming you have installed PHP in your system.

PHPUnit is supposed to be a dev-dependency because testing as a whole should only happen during development.

First off I’m assuming xampp is installed to C:\xampp

1. Open a command prompt and go to C:\xampp\php
2. Type php -v, if you get php version that means PHP is installed otherwise first install PHP.
3. Type pear update-channels (This command will updates all channel definitions)
4. Type pear upgrade (This command will upgrades all existing packages and pear)
5. Type pear channel-discover (This IS phpunit pear)
6. Type pear install --alldeps phpunit/PHPUnit (installs PHPUnit and all dependencies)

PHPUnit 9

The PHPUnit development team announces the immediate availability of PHPUnit 9. This release adds new features, changes and removes existing features, and fixes bugs.

A detailed list of changes is available here

How To Define Methods and Class

Here are a few conventions to get you started:

  • You’ll create a test class named after that class. For example, if I had a Employee class, the test class would be named EmployeeTest.
  • The above class should inherit the PHPUnit\Framework\TestCase class.
  • Individual tests in the class are public methods named with test as a prefix. For example, to test a getEmpName method on the Employee class, the method will be named testGetEmpName.
  • You can use PHPUnit’s method like assertSame to see that some method returns some expected value in the testGetEmpName() method.

How Test Project Using PHPUnit

Let’s create a project and cd into this directory:

$ cd test-project
$ composer init

Define PHPUnit as dev dependency in the package.json file:

"require-dev": {
        "phpunit/phpunit": "^9.5"

The method into Employee.php Class:

public function getEmpName(): string
        return "Emp name is " . $this->name . ".";

Let’s define the test case in EmployeeTest.php class:

public function testGetEmpName()
    $emp = new Employee(18, 'parvez');

    $this->assertStringContainsStringIgnoringCase('parvez', $emp->getEmpName());

How to Run PHPUnit Test Case

You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder.

$ ./vendor/bin/phpunit --verbose tests

One thought on “How To Test PHP Code With PHPUnit

Leave a Reply

Your email address will not be published.