SEO

Unit Testing with PHPUnit

Craig Bullock 21st May 2015

Unit testing with PHPUnit is an integral part to maintaining PHP based projects. PHPUnit is the industry standard testing framework that allows developers to unit test their code. It allows developers to test individual methods or pieces of functionality. This then provides a platform to test a system with while introducing new features that could potentially break exisiting functionality. If some new code introduces a bug, it can then be picked up by your unit tests. This gives developers a powerful tool to use as they build on projects ensuring new functionality can be integrated into systems seemlessly.

PHPUnit can simply be installed with Composer. Simply add a dependency to your composer.json file.


{
    "require-dev": {
        "phpunit/phpunit": "5.0.*"
    }
}

Run composer update and this will download PHPUnit for you.

Writing a simple Unit test can be as easy as the following


<?php
class FooBarTest extends PHPUnit_Framework_TestCase
{
  public function testFoo()
  {
    $foo = true;
    $this->assertTrue($foo);
  }

  public function testBar()
  {
    $bar = false;
    $this->assertTrue($bar);
  }
}

The assertTrue() method tests if an argument is true. In this case testFoo() will pass, while testBar() will fail. Of course this is not actually very helpful for us as this does not tell us anything. However if we have a class we were using with our application that had getFoo() and getBar() methods that we expected return true each time they were called we could then unit test them.


<?php
class MyClass
{
  public function getFoo()
  {
    return true;
  }

  public function getBar()
  {
    return true;
  }
}

So imagine there was some logic in each of these methods that made some comparissons and returned a boolean that we expected to be true each time, we could unit test them like so.


<?php
class FooBarTest extends PHPUnit_Framework_TestCase
{
  protected $myClass;

  public function setUp()
  {
    $this->myClass = new MyClass();
  }

  public function testFoo()
  {
    $foo = $this->myClass->getFoo();
    $this->assertTrue($foo);
  }

  public function testBar()
  {
    $bar = $this->myClass->getBar();
    $this->assertTrue($bar);
  }
}

So we are now testing for return values from a class that is within our application. If a new feature was to change and this had an impact on the return values of one of these methods, we would be able to catch this in our unit tests.

(0) Comments

This article has not received any comments yet.

Have your say

Say Hello