A simple PHPUnit TestCase example

In this article, we will see, how to create and test a simple PHP class, say Calculator, using PHPUnit.

1. Create a directory called Calculator with the given below command

$mkdir Calculator

2. Add Composer to the directory Calculator

First download Composer installer from here and copy it to the directory Calculator. Then execute the given below command to add the dependency management tool.

php installer

3. Add PHPUnit library to this project

Execute the below given below command at the root of the project.

php composer.phar require --dev phpunit/phpunit

4. Enable class autoload for this project

We can enable autoload in our project by adding the autoload construct to composer.json as given below :

   "autoload": {
        "classmap": [

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

5. Create directories src and tests in the root directory of the project

$mkdir src
$mkdir tests

6. Create a class file called Calculator.php in the directory src

    class Calculator{
        public function sum($n1, $n2){
            return $n1 + $n2;

The Calculator class has a method called sum which receives two arguments and returns its sum

7. Create a class filed called CalculatorTest.php in the directory tests

    use PHPUnit\Framework\TestCase;

    class CalculatorTest extends TestCase {

        public function testIsSumCorrect(){
            $calc = new Calculator();
            $result = $calc->sum(1,2.5);
            $expected = 3.5;


The class CalculatorTest has a test, which tests whether the sum function of the Calculator class is correct or not.

8. Running the test

We can run the test by executing the given below command at the root of the project

$./vendor/bin/phpunit --testdox tests/CalculatorTest.php

On executing the test, PHPUnit will display the test result as given below :

A simple PHPUnit Testing

Comments on this post

No comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trackbacks and Pinbacks on this post

No trackbacks.

TrackBack URL