This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

Automate Codeigniter Unit Testing With PHPUnit

May 28, 2021

5 Min Read
codeigniter phpunit

Quality assurance is one of the central aspects of software development. In fact, test-driven development is an entire development methodology developed around the concept of integrating quality assurance within the development cycle. However, before discussing how to automate Codeigniter PHPUnit testing, I will describe the theoretical basis of unit testing and how it adds value to the Codeigniter projects deployed on any web hosting with PHP and MySQL support.

You Might Also Like: Unit Testing in PHP With PHPUnit

What’s a Unit?

A unit is a component of the overall code of the project. In many cases, an entire module is considered a single unit. However, for many projects, individual classes or even individual methods could be taken as a single unit.

Each unit is tested independently to ensure that it works as it is planned. The idea is to make sure that all “units” of the codebase are correctly coded and behave they should. Once every unit is tested and verified, the overall codebase works perfectly.

Why Codeigniter Unit Testing in Important?

Unit testing has become a very important quality assurance methodology for Codeigniter projects. Project managers and developers could breakup the larger codebase into manageable chunks that could then be rigorously evaluated to pre-set standards.

You Might Also Like: Continuous Integration in PHP Using TravisCI

Discover Problems Early On

The good thing about Codeigniter unit testing is that it could be initiated in parallel with the development phase. In fact, as soon as a unit is shipped out by the developers, it can be tested. Thus, instead of waiting till the end of the development phase, project managers can discover and rectify bugs without affecting the final product.

Simplified Design & Development

Codeigniter PHPUnit testing ensures that the overall project design and development is simple and easy-to-understand for all stakeholders. Once the testing phase kicks in, the overall direction of the project could be evaluated and corrected if things go wrong. Similarly, since the project could be divided into smallest unit, the problems that slipped through the cracks get caught as soon as the unit goes for testing.

Start Growing with Cloudways PHP Hosting Today

People Love us because we never compromise on hosting

On-track Documentation

Documentation has always been the thorny issue of development projects. In many cases, documentation is postponed till the very end of the project, at which time it is too late. In a unit testing environment, the project team has the results of the testing of individual units and thus could create project’s documentation in pieces that could finally be compiled into the MAN file or similar documentation structure.

Limitations of Codeigniter Testing

No testing methodology is perfect and Codeigniter PHPunit testing is no different. Unit testing has several limitations that every project manager should keep in mind.

Loss of Scope

It is easy to loose the big picture while working with the pieces. This is a common drawback of using unit testing exclusively for quality assurance. Experts suggest that unit testing should be supplemented by other testing paradigms.

Too Much Effort – Too Little Gains

As a rule of thumb, testing a line of single line of code requires writing about four lines of testing code. In many cases, this is worth the effort but the overall impact of writing so much code that is not part of the shippable product.

Buggy Test Code

Ironically, buggy test code is a common enough occurrence and is considered a serious drawback of the paradigm. However, this could be mitigated by opting for an automated testing framework that minimizes the possibility of error in testing code.

You Might Also Like: Running Unit Testing in Laravel

Why Automate Unit Testing for Codeigniter Projects

Automation Test

Here is an example of automation testing.  As you can see, an important part of this example is ConfigSingleton class. This configuration class is used to generate values. The success (or failure) of the functions is dependent upon the values produced by the class. However, a better option is to pass a $config argument that consists of a config object with the required configuration.

Another important aspect to consider is the nested IF conditions. If you look closely you will realize that each branch created by the IF statement opens up a new test scenario. In many cases, these scenarios are related and test a connected scenario.

function cw_page_distinct($property_type = 'index')


   $file_distinct = ConfigSingleton::$config_distinct_site . "$property_type.php";

   $confined_file  = ConfigSingleton::$config_save_path;

   if ($txt = file_get_contents($file_distinct)) {

       if ($want_save_value = preg_match('//', $content_value)) {

           if (file_exists($confined_file)) {

               $fh = fopen($confined_file, 'w+');

               fwrite($fh, $want_save_value);


               return TRUE;

           } else {

               return FALSE;


       } else {

           return FALSE;




Configuration Objects

Configuration object often forms the basis of the Codeigniter unit testing processes. in fact, many experts recommend that this should be the starting point of the unit testing process. In many cases, the configuration objects could be utilized through the unit testing could be utilized through a class. For the purpose of this tutorial, I have created the following class:

class DistinctParser() {

   protected $native_path;

   protected $distinct_path;

   protected $config;

   public function __construct(ConfigObj $config) {

       $this->config = $config;


   public function set_native_path($filename) {

       $file = filter_var($filename);

       $this->local_path = $this->config->local_path . "/$file.html";


   public function set_distict_path($filename) {

       $file = filter_var($filename);

       $this->remote_path = $this->config->remote_site . "/$file.html";


   public function get_distinct_path_src() {

       if ( ! $this->remote_path) {

           throw new Exception("Distinct File not set");


       if ( ! $this->local_path) {

           throw new Exception("Native file not set");


       if ( ! $distinct_src = file_get_contents($this->remote_path)) {

           throw new Exception("Problem in distinct file");


       return $distinct_src;


   public function parse_remote_src($src='') {

       $src = filter_validate($src);

       if (stristr($src, 'value_we_want_to_find')) {

           return array('val1', 'val2');

       } else {

           return FALSE;



   public function get_remote_path() {

       return $this->remote_path;


   public function get_local_path() {

       return $this->local_path;


  • public function __construct(ConfigObj $config) → Class constructor — forces injection of $config object
  • public function set_native_path($filename) → Setter for local_path property
  • public function set_distict_path → Setter for remote_path property
  • public function get_distinct_path_src()  → Retrieve the remote source
  • public function parse_remote_src → Parse a source string for the value
  • public function get_remote_path() →  Getter for remote file path property
  • public function get_local_path() →  Getter for local file path property

Test Cases

Now that you have an idea of how to set up Codeigniter unit testing, it is time to mention test cases. At this point, you will start creating test cases.

A test case is a single (and often isolated) piece of code that determines whether a particular function or condition is valid under pre-set conditions. The good thing is that test cases could be written to  test almost all areas of your Codeigniter project.

You Might Also Like: Passing Data From Controller to View in CodeIgniter

I have written the following test case to test the controller of the application. You can see that it actually extends the default Codeigniter controller class.

class Testcase extends  CI_Controller


public function get_testcase(){

    $this ->load ->view('view_testcase');



Put the above code snippet in a file named Testcase.php. Next, I will create Checkunit_text.php to test the get_testcase(). Here is the code:

class Checkunit_test extends  UnitTest


public function unit_test_check()


       $output=$this -> request('GET',['Testcase','get_testcase']);

    $expected = 'Unit Test';

    $this -> assertContains($expected,$output);



Create the View

The next step is the creation of view. For this, use the following simple code:


define('BASEPATH') OR exit('access not allowed');


Run The Codeigniter PHPUnit Test

  • open terminal OR cmd
  • type the command $cd application/testcase/(application folder name)
  • command to run the test  → $ phpunit –phpunit

Final Words

So coming to the end of this blog, we have briefly seen how we can initiate Codeigniter PHPUnit testing automation. The blog gives a detailed review how to streamline testing workflows and why Codeigniter unit testing hold a great value in applications. If you still have further questions regarding this article or automation testing in Codeigniter, feel free to write down your comments below in the comments section.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Customer Review at

“Cloudways hosting has one of the best customer service and hosting speed”

Sanjit C [Website Developer]

Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at [email protected]


Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!


Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!