PHPUnit Testing
Blog

Understanding PHPUnit and How to write Unit test cases

Every developer knows how painful bugs can be, especially in the production stage as it takes hours of hard work. Though the development team always give their best to work out the bugs in the development process, a number of bugs creep in the code. So what could be done to fix these bugs and eliminate the repetitive task of manual testing? Here one way is to go for Unit Testing - a well-known methodology to write unit test cases in PHP. 

PHPUnit is a programmer-oriented testing framework. This is the outstanding testing framework for writing Unit tests for PHP Web Applications. With the help of PHPUnit, we can direct test-driven improvement.

RelatedHow to Write PHP Unit Tests for Drupal 8

Before diving into PHPUnit, let’s have a look at types of testing.

Types of Testing

Testing is about verifying a product to find out whether it meets specified requirements or not. Typically, there are four types of testing:

  1. Unit Testing
  2. Functional Testing
  3. Integration Testing
  4. Acceptance Testing

Unit Testing: Analysing a small piece of code is known as Unit Testing. Each unit test targets a unit of code in isolation. Unit testing should be as simple as possible, and it should not be depended on another functions/classes. 

Functional Testing: Testing based on functional requirements/specifications is called functional testing. Here we check given tests providing the same output as required by the end-user.

Integration Testing: It is built on top of Unit Testing. In Integration testing,  we combine two units together and check whether the combination works correctly or not. The purpose of this testing is to expose faults in the interaction between integrated units.

Acceptance Testing: This is the last phase of the testing process. Here we check the behavior of whole application from users side. End users insert the data and check the output whether it meets the required specifications or not. They just check the flow, not the functionality.

RelatedUnit Testing improves your product quality with 9 ways

Why write Unit Tests

One of the main benefits of writing Unit tests is that it reduces bugs on new and existing features. The Unit Testing identifies defect before the code is sent for integration testing. It also improves the design. By unit testing, we can find the bugs in an early stage that will eventually reduce the cost of bug fixings. It also allows developers to refactor code or upgrade system. Further, it makes development faster and improves the quality of the code.

PHPUnit: Writing unit tests manually and running them often take more time. For this, we need an automation tool like Selenium. PHPUnit is currently the most popular PHP unit testing framework.

It provides various features like mocking objects, code coverage analysis, logging etc. It belongs to xUnit libraries. You can use these libraries to create automatically executable tests, which verifies your application behavior.

Installing PHPUnit (Prerequisites)

  • Use the latest version of PHP.
  • PHPUnit requires dom, JSON, pcre, reflection and spl extensions, which are enabled by default.

Installation (Command line interface)

Download PHP Archive (PHAR) to obtain PHPUnit. To install PHAR globally, we can use the following commands in command line.

$ wget https://phar.phpunit.de/phpunit-6.5.phar
$ chmod +x phpunit-6.5.phar
$ sudo mv phpunit-6.5.phar /usr/local/bin/phpunit
$ phpunit --version

Via Composer

If you have installed composer in your system you can download it by using the single command.

composer require --dev phpunit/phpunit

There are a lot of assertions and annotations methods available in PHPUnit, let’s have a look on some we can use. 

Assertions

PHPUnit assertion methods are regular methods that return either true or false after evaluating the code you have passed.

assertEmpty(mixed $actual[,string $message=’ ’])  It return an error if $actual is not empty.

Example:
 Output:

PHPUnit Assertion


The Test is failed because the array is not empty.

assertEquals(mixed $expected,mixed $actual[,string $message=’ ’])

It gives an error when $expected is not equal to $actual. If $expected equals $actual then it returns true.

Example:

Output:

PHPUnit Assertion 2

This is failed because 1 is not equal to 0 and bar is not equal to baz.

Annotations


@dataProvider
Arbitrary arguments are accepted by the test method. These arguments are provided by data provider method, which is a public and returns an array of arrays or objects. We can specify the data provider method by @dataProvider annotation.

Example For Data provider:

Git link:
 OutPut:

PHPUnit Annotation

In the above code snippet, addition Provider is data Provider. We can use one provider as many times as we want.

@depends()

PhpUnit supports explicit dependencies between test methods. By using @depends annotations, we will be depended on test methods.

Example: 

Output:

PHP unit

In the above example, we are declaring one variable in testEmpty() and using the same variable in dependency methods. testPush() method depends on testEmpty() as the outcome can be used in  testPush() method. 

The class of the tests goes into ClassTest. This class inherits from PHPUnit\Framework\TestCase. Test methods are public and every method should start with test*. Inside these methods, we use assertion methods. Note that annotations are used before the method.

PHPUnit @depends


Setup() and TearDown() methods:

We can share the code for every test method. Before running every test method, setup() template method is invoked. setup () method creates objects which we test. After every test method running whether it is failed or successful, teardown template method is invoked. teardown() template method clean the objects.

Example for Setup() and TearDown methods:

In the above example, we are declaring one instance variable $name and using that code in all other test methods.

If the setup() method code differs slightly, then change the differ code in the test method. If you want different setups for test methods, then you need another test case class. At this point, we’re ready to begin building PHPUnit to make writing unit tests easier and improve software Quality.

Hope you find this “Introduction to Unit testing” helpful. Unit Testing is a vast topic. Here I have given you a brief introduction so that you can start writing your own tests. Please comment below if you have any question or suggestions.

Below is the given presentation on "Getting Started With PHPUnit Testing".