Turn your manual testers into automation experts Request a DemoStart testRigor Free

CodeIgniter Testing

CodeIgniter Testing

CodeIgniter is an open-source and rapid-development web framework for developing professional and interactive websites with minimum footprint. EllisLab launched CodeIgniter and is currently a British Columbia Institute of Technology project.

CodeIgniter has rich libraries, simple interfaces, helpers, and logical structures to simplify complex PHP functions. It is loosely based on the MVC (Model-View-Controller) platform, where Controller is necessary, and View is optional.

CodeIgniter-Architecture
A CodeIgniter website may require below testing types:

Unit Testing

In unit testing, the focus will be on individual units or components of the application which are logically isolated. Unit testing is the first level of testing, and developers will usually do it.

For CodeIgniter, you can perform unit testing through the following tools:

  • Unit Testing Class
  • PHPUnit

Unit Testing Class

CodeIgniter's Unit Test class consists of an evaluation function and two result functions. It's straightforward and not feature-rich like PHPUnit. It helps verify that the code produces the correct data type and results. Below are the steps to use the Unit Test class.

Step 1: Initialize the Unit Test class in your controller using the library function.
$this->load->library('unit_test');
Step 2: Run the test by providing the test and expected result in the script. Here is a sample script to identify the datatype. You can give a literal or data type match for the expected result.
$test = 1 + 1;
$expected_result = 2;
$test_name = 'Adds one plus one';
$this->unit->run($test, $expected_result, $test_name);

Step 3: Generate the results and view them through any of the following methods:

Echo Command

To directly show a report, echo the run function as below:
echo $this->unit->run($test, $expected_result);

Strict Mode

By default the unit test class evaluates literal matches loosely. To enable strict mode, use the below script:
$this->unit->use_strict(TRUE);

Unit Test Display

When using Unit Test Display, customize the test results using
$this->unit->set_test_items()

Additionally, you can create one template and decide the formatting of test results. Know more about Unit Testing Class here.

PHPUnit

CodeIgniter provides in-built support for PHPUnit for testing. PHPUnit can be installed using any of the two methods:

  • Composer: Install PHPUnit into your project using Composer
  • Phar: Download the standalone .phar file from the PHPUnit website

PHPUnit framework's configurations are saved by default in the phpunit.xml.dist file in the project root. You can override the configuration in your phpunit.xml file.

All the tests are located in the tests/app directory. Test a new library using the path tests/app/Libraries/CheckUnitTest.php.
class Testcase extends  CI_Controller {
  
  public function get_testcase() {
    $this ->load ->view('view_testcase');
  }

  public function unit_test_check() {
    $output=$this -> request('GET',['Testcase','get_testcase']);
    $expected = 'Unit Test';
    $this -> assertContains($expected,$output);
  }

}

Integration Testing

It focuses on testing different units, modules, or components of the software application as a combined entity. The focus is testing the interfaces and exposing the bugs when the components are integrated and interact.

You can perform integration testing for CodeIgniter applications by testing:

  • Database Integrations
  • Controllers
  • HTTP Features
  • Responses

Database Integrations

Use the DatabaseTestTrait class and extend CIUnitTestCase to take advantage of CodeIgniter's built-in database tools. Use the setUp() and tearDown() phases for configuring the pre-condition and cleaning it back to the default state.

The DatabaseTestTrait class provides several helper methods to support CodeIgniter database testing.
<?php
namespace App\Database;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\DatabaseTestTrait;

class MyTests extends CIUnitTestCase
{
  use DatabaseTestTrait;

  protected function setUp(): void
  {
    parent::setUp();
    // Do something here....
  }

  public function test_basic_example()
  { 
    $response = $this->get('/');
    // ...
  }
  
  protected function tearDown(): void
  {
    parent::tearDown();
    // Do something here....
  }
}

Controllers

CodeIgniter provides valuable helper classes and traits to test the controllers. Enable controller testing by using ControllerTestTrait within the tests. This trait provides many useful helper methods, and you can then set up the environment, including the request and response classes, the request body, URI, etc.

See a sample controller test script below:
<?php
namespace CodeIgniter;

use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\ControllerTestTrait;
use CodeIgniter\Test\DatabaseTestTrait;

class TestControllerA extends CIUnitTestCase
{
  use ControllerTestTrait;
  use DatabaseTestTrait;
  public function testShowCategories()
  {
    $result = $this->withURI('http://example.com/categories')
        ->controller(\App\Controllers\ForumController::class)
        ->execute('showCategories');
    $this->assertTrue($result->isOK());
  }
}

HTTP Features

Feature testing allows viewing the results of a single call to the application, e.g., results of a single web form or an API endpoint. It is helpful since it allows testing the entire life cycle of a single request.

For feature testing, the test class should use CodeIgniter\Test\DatabaseTestTrait and CodeIgniter\Test\FeatureTestTrait traits. Use setUp() and tearDown() phases if implementing custom methods.

See a sample script for HTTP features testing below:
<?php
namespace App;

use CodeIgniter\Test\DatabaseTestTrait;
use CodeIgniter\Test\FeatureTestTrait;

class TestFoo extends CIUnitTestCase
{
  use DatabaseTestTrait;
  use FeatureTestTrait;
  
  protected function setUp(): void
  {
    parent::setUp();
    $this->myClassMethod();
  }

  public function test_basic_example()
  { 
    $result = $this->call('get', '/');
    $result = $this->call('post', 'contact', [
      'name'  => 'Fred Flintstone',
      'email' => 'flintyfred@example.com',
    ]);
  }

  protected function tearDown(): void
  {
    parent::tearDown();
    $this->anotherClassMethod();
  }
}

Responses

CodeIgniter includes a TestResponse class for parsing and testing the application responses. TestResponse class provides the result for Controller and HTTP feature tests. Using ResponseInterface, you can create custom test responses too.

The TestResponse class also has different in-built assertions. If the responses have JSON or XML format, you can handle them using the inbuilt functions provided by the class.

End-to-End Testing

In this testing, the approach is from an end-user perspective and will simulate real user scenarios. The focus will be testing the user scenarios, which integrate the Model, View, and Controller seamlessly.

Perform E2E testing using any of the legacy automation testing tools.

Traditional (Legacy) Automation Testing Tools

Selenium has enjoyed the popularity of being the most used automation tool. It requires a strong background in programming and can be used only for web testing. Dependency on XPath and CSS locators contributes significantly to unstable test scripts and rework. All these factors require massive and unavoidable maintenance efforts to keep the test scripts functional.

Most test automation tools today are based on Selenium and directly inherit its disadvantages. Many other Selenium limitations are causing a shift of interest toward codeless automation tools like testRigor.

New Generation Tools

testRigor is a new era no-code automation tool with integrated AI that helps create automated test cases much faster and spend nearly no time on maintenance. Use testRigor's generative AI-based test script generation, where you only need to provide the test case title and the steps will be automatically generated within seconds.

Below are some advantages of testRigor over other tools:

Versatile test creation: Select from three convenient ways to create tests - write tests yourself in plain English, use the test recorder, or employ generative AI for test creation.

Ultra-stable: testRigor employs no-code test scripts, eliminating dependencies on any specific programming language. Elements are referenced as they appear on the screen, thereby reducing reliance on implementation details. This greatly simplifies the process of test creation , maintenance, and debugging.

Cloud-hosted: Save time, effort, and resources on infrastructure setup. With testRigor, you are ready to start writing test scripts right after signing up, boasting a speed up to 15 times faster compared to other automation tools.

Comprehensive testing coverage: testRigor supports all main types of testing and accommodates cross-browser and cross-platform tests.

Seamless integrations: built-in integrations with CI/CD, ERP, and test management tools ensure a seamless and efficient testing process.

Get a glimpse of testRigor's incredible features.

See a simple testRigor test script below:
// Buy from a cloth retail website
login
check that page contains "Striped Black Shirt"
click "Striped Black Shirt"
click "Add to cart"
click "Cart"
click "Place Order"
check that page contains "Order placed successfully."

The simplicity of the test script is what catches the eye. No CSS or XPath locators, just plain text as visible on the UI. The auto-healing capabilities automatically handle the changes in the element attributes. So next time, if the div changes to li, testRigor still identifies the element easily without breaking the test script.

You can cover much more complex scenarios too. Take a look at the documentation to get a better understanding of the supported functionality.

Conclusion

"More than the act of testing, the act of designing tests is one of the best bug preventers known. The thinking that must be done to create a useful test can discover and eliminate bugs before they are coded - indeed, test-design thinking can discover and eliminate bugs at every stage in the creation of software, from conception to specification, to design, coding, and the rest."
- Boris Beizer

The quote above emphasizes good test design. To think and devote more time to test design, a tester needs to shift focus from programming automation test scripts. Codeless AI-enabled tools like testRigor provide an advantage to focus more on test case design since testRigor takes care of the test scripting, environment handling, maintenance, reporting, and everything else!

Its incredible features aid in catching more relevant bugs early in the software development cycle and subsequently reduce the application's overall cost-to-market.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.