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.

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Secure Any CMS With Ease with Our Malware Protection Add-On! LEARN MORE→

How to Automate Codeigniter Unit Testing With PHPUnit

Updated on May 28, 2021

5 Min Read

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.

Unit testing is an approach to computer program improvement in which tests are composed for each work in your application. In case you’re not familiar with the concept, you might do a little research on the subject. CodeIgniter’s Unit Test course is very basic, comprising assessment work and two result functions.

Codeception is a multi-featured testing framework for PHP. It can handle unit, functional, and acknowledgment testing of web applications, and it’s powered by the already exceptionally well-known PHPUnit testing system

What’s a Unit?

Unit testing is a software test in which code squares are checked to see whether the created result matches the desires. The units are tried by composing a special test case. The unit test is generally programmed but may well be actualized manually.

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 it works as planned. The idea is to ensure that all “units” of the codebase are correctly coded and behave as they should. Once every unit is tested and verified, the overall codebase works perfectly.

Why Is Codeigniter Unit Testing Important?

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

Discover Problems Early on

The good thing about Codeigniter unit testing is that it can 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 are simple and easy to understand for all stakeholders. Once the testing phase kicks in, the project’s overall direction could be evaluated and corrected if things go wrong. Similarly, since the project could be divided into the smallest unit, the problems that slip 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 a thorny issue in development projects. Documentation is often postponed until the very end of the project when 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 the 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 lose 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 a 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 is.

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.

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 depends 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);

               fclose($fh);

               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 unit testing or 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 know 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.

I have written the following test case to test the application’s controller. 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 a view. For this, use the following simple code:

<?php

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

Summary

So coming to the end of this blog, we have briefly seen how we can initiate Codeigniter PHPUnit testing automation. The blog reviews how to streamline testing workflows and why Codeigniter unit testing holds 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

Owais Khan

Owais works as a Marketing Manager at Cloudways (managed hosting platform) where he focuses on growth, demand generation, and strategic partnerships. With more than a decade of experience in digital marketing and B2B, Owais prefers to build systems that help teams achieve their full potential.

×

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!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

Peak Performance.

Limitless Scalability.

  • 0

    Days

  • 0

    Hours

  • 0

    Mins

  • 0

    Sec

Off For 4 months
+40 free Migrations

Claim Now