Working with PHPUnit for Your Porject

Rikzan Fernanda
2 min readSep 25, 2021

PHPUnit is a unit testing framework for the PHP programming language. Testing is an important part of PHP application development but I think many PHP developers don’t test because they consider testing is an unnecessary burden and requires too much time for too few benefits.

Why Do We Test?
We do tests to ensure that our PHP applications work, and continue to work, according to our expectations. It is as simple as that.

When Do We Test?
Tests should be done before development, during development, and after development.

So, after reading the reasons above, I hope you understand how important is it.
In this article, I will show you how do we using PHPUnit for our projects. Please ensure that you have composer installed on your computer.

Installation PHPUnit
Firstly, we need the framework of PHPUnit. The page of PHPUnit can be found at https://phpunit.de/.
Open your CLI and navigate to your project path, then run:
composer require phpunit/phpunit

After downloading the file, we will see there are vendor folder and composer.json file, in this case, I am using PHP 7.4.15.

Create a file that you want to test
Create an src folder and create a PHP file with name Calculator.php, the following is the code:

<?phpclass Calculator
{
public function add(float $a,float $b): float
{
return $a + $b;
}
public function sub(float $a,float $b): float
{
return $a - $b;
}
}

Tests
Create a test folder in your project. The tests folder is for the place you put all classes or files for testing. Create PHP file with name CalculatorTest.php, and the following is the code:

<?php
require_once '../app/Calculator.php';
class CalculatorTest extends PHPUnit\Framework\TestCase
{
public function testAdd()
{
$calc = new Calculator();
return $this->assertEquals(4, $calc->add(2.5, 2.5));
}
public function testSub()
{
$calc = new Calculator();
return $this->assertEquals(1, $calc->sub(4.5, 3));
}
}

Run PHPUnit
Open your CLI and navigate into the tests folder, then run:

..\vendor\bin\phpunit CalculatorTest.php

We will see the error because we wrote the wrong code for the expectation param. See the code below:

...
return $this->assertEquals(4, $calc->add(2.5, 2.5));
...
return $this->assertEquals(1, $calc->sub(4.5, 3));

We change them with this code:

...
return $this->assertEquals(5, $calc->add(2.5, 2.5));
...
return $this->assertEquals(1.5, $calc->sub(4.5, 3));

Open your CLI again and run it again.
You will see that there are no error warning for the test, is it means that your code runs successfully according to with the expected output.

Okay, Guys, I can’t believe we’ve reached the end of the article.
Thank you very much, I hope this article is useful.

--

--

Rikzan Fernanda
0 Followers

Web developer from Indonesia. I like to share my knowledge about programming especially web app.