PHPUnit Testing for PHP Applications (Test for Bugs & Quality)

PHPUnit is a framework used for unit testing in PHP applications. PHPUnit is a go-to tools for PHP developers for automated testing of code. Learn how to use PHPUnit test to ensure code quality in PHP applications.

PHPUnit Testing for PHP Applications

When working with PHP applications it is important to write reliable, maintainable and bug free code. One of the most effective and used way is PHPUnit testing which allows developers to write test cases like methods or functions to ensure they work as expected. We will walk through an example to understand PHPUnit Testing in PHP applications to automate the testing of code.

 

Why PHPUnit Testing is Essential for PHP Applications

PHPUnit testing is a crucial part of modern web applications to ensure code works as intended. By writing unit tests, it becomes easy to detect bugs in early stages, reduces the risk of error in production and helps to improve code quality and reliability. Automated PHPUnit testing also make it faster to run all tests at once which is easier and saves time as compared to than manually testing each code block in application. 

 

PHPUnit - Unit Testing PHP Applications for Bugs & Quality

PHPUnit helps identify bugs in early stages of development. With PHPUnit it is possible to test pieces of code or functionality separately ensuring each component is working correctly. We will first install and setup PHPUnit and then write a simple unit test as an example.

 

Install and Setup PHPUnit Framework 

Lets start by installing PHPUnit framework via composer with following command: 

composer require --dev phpunit/phpunit

After installation PHPUnit can be run from project's local vendor/bin directory like as below:

./vendor/bin/phpunit

It is also possible to create a phpunit alias or script like this:

"scripts": {
"test": "phpunit"
},

Now the tests can be run using the following command:

composer test

Now next step is to setup PHPUnit configuration by creating phpunit.xml file in project's root directory. This file tells PHPUnit where to find tests and how to run them. The content of this file should look something like this:

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

Create a PHPUnit Test Class, Writing Test Methods

The PHPUnit tests are categorized into classes that corresponds to the classes that are supposed to run tests. These classes are to exist in the directory defined in phpunit.xml file. Lets create an example unit test class with name ExampleTest that contains some basic unit test methods for understanding.

  • Create a PHP class ExampleTest.php for tests.
  • Add a method testAddition() as an example test to demonstrate how assertions in PHPunit work.
  • Add a method testUrlStatusCode() to test response code of a URL. This test method can be used to ensure certain URLs are returning expected response code.
  • Add a method testApiResponseStructure to test API response structure. This test can be used to ensure the API response returns the expected response code, contains all the expected keys and all values are in expected format.
<?php

use GuzzleHttp\Client;
use PHPUnit\Framework\TestCase;
class ExampleTest extends TestCase
{
public function testAddition()
{
$result = 5 + 5;

$this->assertEquals(10, $result);
}

public function testUrlStatusCode()
{
$client = new Client();

$response = $client->get('https://jsonplaceholder.typicode.com/posts/1', [
'verify' => false
]);

$this->assertEquals(200, $response->getStatusCode());
}

public function testApiResponseStructure()
{
$client = new Client();

$response = $client->get('https://jsonplaceholder.typicode.com/posts/1', [
'verify' => false
]);

$this->assertEquals(200, $response->getStatusCode());

$data = json_decode($response->getBody(), true);

// Check that required keys exist
$this->assertArrayHasKey('userId', $data);
$this->assertArrayHasKey('id', $data);
$this->assertArrayHasKey('title', $data);
$this->assertArrayHasKey('body', $data);

// Validate data types
$this->assertIsInt($data['userId']);
$this->assertIsInt($data['id']);
$this->assertIsString($data['title']);
$this->assertIsString($data['body']);
}
}
 

Understand PHPUnit Assertions

Assertions in PHPUnit check whether the actual output of your code matches the expected output. Following are some commonly used assertions:

  • assertEquals($expected, $actual): Asserts that two values are equal.
  • assertTrue($condition): Asserts that the condition is true.
  • assertFalse($condition): Asserts that the condition is false.
  • assertNull($value): Asserts that a value is null.
  • assertContains($needle, $haystack): Asserts that a value is found in an array or string.
  • assertCount($expectedCount, $array): Asserts that the number of elements in an array is equal to the expected count.

We demonstrated how to install and setup PHPUnit tests and write unit tests to ensure quality and reliability of a PHP application. By making PHPUnit testing a core part of development bugs can be identified in early stages of development and quality of code can be improved efficiently.