Basics of Unit Testing With PHPUnit

In this tutorial, you will learn how to write your first unit test in PHP programming language via the PHPUnit framework. In the Software Development Life Cycle or SDLC, unit testing is a methodology by which each and every unit of source code will be tested for accuracy. In response to "What's a unit of code?", we are typically talking about the smallest part of a source code which is a function or method that can be used separately.

Generally speaking, experienced developers care about unit testing because it ensures their source code works correctly in any situation due to the fact that tests are run multiple times after adding new features to the code base or after modifying existing ones. It also reduces bugs or issues in the production environment because they are caught before the real users can see them.

Installing PHPUnit

As this tutorial is written for a GNU/Linux environment, the following steps are just for Linux users. Before installing PHPUnit, you need to make sure that you have installed PHP 5.6 or higher plus Composer. To install this package manager globally on your machine, you can easily run the following command in the terminal:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

By running composer -v in the terminal, you can find the version of Composer which has been installed on your system.

To start the installation, go to /var/www and create a directory with whatever name you want such as phpunit then go inside and run the following command:

$ composer require --dev phpunit/phpunit

From now on, the folder structure of this project is as follows:

phpunit
├── composer.json
├── composer.lock
└── vendor

The next step is to create two new directories inside phpunit with whatever name you want such as src and tests so that we will have:

phpunit
├── app
├── composer.json
├── composer.lock
├── tests
└── vendor

To configure PHPUnit framework, we need a file called phpunit.xml in the root of the project which includes at least the following lines:

<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="./vendor/autoload.php"
         colors="true"
         verbose="true"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Test Suite">
            <directory>./tests/</directory>
        </testsuite>
    </testsuites>
</phpunit>

The bootstrap attribute shows the starting point of the application which is autoload.php and <directory>./tests/</directory> defines the route in which all tests reside in. Now open composer.json and complete it as follows:

{
    "require-dev": {
        "phpunit/phpunit": "^8.1"
    },
    "autoload": {
        "psr-4": {
            "Source\\": "src"
        }
    }
}

The autoload key specifies the namespace of the project. In other words, whenever you use the Source namespace, it will be mapped with src folder. Then you need to run the following command:

$ composer dump-autoload -o

Now we are ready to write our first test; so go to src folder and create a file named Calculator.php with the following code:

<?php
namespace Source;

class Calculator
{
    public function addUp(int $firstDigit, int $secondDigit)
    {
        return $firstDigit + $secondDigit;
    }
}

First of all, we define a namespace for the file to be able to use it via Autoloader easily in the future. There is a simple function called addUp() in this class which adds up the parameters and returns the result. Then go to the tests folder and create a file called SampleTest.php and write the following lines in it:

<?php
use PHPUnit\Framework\TestCase;
use Source\Calculator;

class SampleTest extends TestCase
{
    public function testAddUpMethod()
    {
        $cal = new Calculator();
        $this->assertEquals(4, $cal->addUp(2, 2));
    }
}

Bear in mind that all testing classes must end in Test keyword. In line 3 also we have imported the TestCase class from the PHPUnit framework because we are going to extend our class from it. We have created a method called testAddUpMethod() that is going to test the functionality of addUp() function in Calculator class (Be careful that all test functions need to start with the test keyword.)

Within the test function, we have created a new object from Calculator class called $cal and in the next line, we have called assertEquals() from TestCase class which evaluates whether its parameters are equal. Now we run our test with the following command:

$ ./vendor/bin/phpunit 
PHPUnit 8.3.3 by Sebastian Bergmann and contributors.

Runtime:       PHP 7.3.7-2+ubuntu18.04.1+deb.sury.org+1
Configuration: /var/www/phpunit/phpunit.xml

.                                                                   1 / 1 (100%)

Time: 22 ms, Memory: 4.00 MB

OK (1 test, 1 assertion)

As you can see, 1 test and 1 assertion have been done successfully.

by Behzad Moradi on 2019-08-07