Mohammad Emran Hasan
Mohammad Emran Hasan


Mohammad Emran Hasan


A clean way of integrating PHPUnit 3.5.x with CodeIgniter 2.x

Mohammad Emran Hasan's photo
Mohammad Emran Hasan
·Jan 20, 2012·

2 min read

Now a days, my default choice of framework is always Zend Framework. However, I have to maintain a couple live projects in CodeIgniter from early days. I feel its very important to have tests around critical applications, so I have attempted a couple times to integrate PHPUnit with CodeIgniter but failed every time – well, until now.

I’ve managed it this time with hooks. It provides a clean way of bootstrapping the framework and then performing tests on the Model layer – for me testing the model layer has been sufficient. The use is very simple as it does not require any change in how a regular CodeIgniter application is built.

Grab the code from github.

Example – /tests/PostTest.php

CI = &get_instance(); $this->CI->load->database('testing'); }

public function testGetsAllPosts()
    $posts = $this->CI->post->getAll();
    $this->assertEquals(1, count($posts));


How it works

  • The provided PHPUnit bootstrap file sets the CI environment as testing and then loads the framework normally – the code is taken directly from the index.php file.
  • A _display_override_ hook checks if the environment is set to testing or not and when it is, it refrains from outputting the rendered view file
  • The PHPUnit test case file now can get a reference of the CI object using the commonly used _&get_instance()_ method and can load models and other libraries as needed.
  • It is good to have separate database configuration for testing and it might be useful to load the test database with fresh data every time test runs – it can be easily added in the setUp method using the Database Forge classes

Let me know what you think!

Share this