Testing

CodeIgniter has been built to make testing both the framework and your application as simple as possible.Support for PHPUnit is built in, and the framework provides a number of convenienthelper methods to make testing every aspect of your application as painless as possible.

System Set Up

Installing phpUnit

CodeIgniter uses phpUnit as the basis for all of its testing. There are two ways to installphpUnit to use within your system.

Composer

The recommended method is to install it in your project using Composer. While it’s possibleto install it globally we do not recommend it, since it can cause compatibility issues with other projects on yoursystem as time goes on.

Ensure that you have Composer installed on your system. From the project root (the directory that contains theapplication and system directories) type the following from the command line:

  1. > composer require --dev phpunit/phpunit

This will install the correct version for your current PHP version. Once that is done, you can run all of thetests for this project by typing:

  1. > ./vendor/bin/phpunit

Phar

The other option is to download the .phar file from the phpUnit site.This is a standalone file that should be placed within your project root.

Testing Your Application

PHPUnit Configuration

The framework has a phpunit.xml.dist file in the project root. This controls unittesting of the framework itself. If you provide your own phpunit.xml, it willover-ride this.

Your phpunit.xml should exclude the system folder, as well as any vendor orThirdParty folders, if you are unit testing your application.

The Test Class

In order to take advantage of the additional tools provided, your tests must extend \CIUnitTestCase. All testsare expected to be located in the tests/app directory by default.

To test a new library, Foo, you would create a new file at tests/app/Libraries/FooTest.php:

  1. <?php namespace App\Libraries;
  2.  
  3. class FooTest extends \CIUnitTestCase
  4. {
  5. public function testFooNotBar()
  6. {
  7. . . .
  8. }
  9. }

To test one of your models, you might end up with something like this in tests/app/Models/OneOfMyModelsTest.php:

  1. <?php namespace App\Models;
  2.  
  3. class OneOfMyModelsTest extends \CIUnitTestCase
  4. {
  5. public function testFooNotBar()
  6. {
  7. . . .
  8. }
  9. }

You can create any directory structure that fits your testing style/needs. When namespacing the test classes,remember that the app directory is the root of the App namespace, so any classes you use musthave the correct namespace relative to App.

Note

Namespaces are not strictly required for test classes, but they are helpful to ensure no class names collide.

When testing database results, you must use the CIDatabaseTestClass class.

Additional Assertions

CIUnitTestCase provides additional unit testing assertions that you might find useful.

assertLogged($level, $expectedMessage)

Ensure that something you expected to be logged actually was:

  1. $config = new LoggerConfig();
  2. $logger = new Logger($config);
  3.  
  4. ... do something that you expect a log entry from
  5. $logger->log('error', "That's no moon");
  6.  
  7. $this->assertLogged('error', "That's no moon");

assertEventTriggered($eventName)

Ensure that an event you expected to be triggered actually was:

  1. Events::on('foo', function($arg) use(&$result) {
  2. $result = $arg;
  3. });
  4.  
  5. Events::trigger('foo', 'bar');
  6.  
  7. $this->assertEventTriggered('foo');

assertHeaderEmitted($header, $ignoreCase=false)

Ensure that a header or cookie was actually emitted:

  1. $response->setCookie('foo', 'bar');
  2.  
  3. ob_start();
  4. $this->response->send();
  5. $output = ob_get_clean(); // in case you want to check the adtual body
  6.  
  7. $this->assertHeaderEmitted("Set-Cookie: foo=bar");

Note: the test case with this should be run as a separate processin PHPunit.

assertHeaderNotEmitted($header, $ignoreCase=false)

Ensure that a header or cookie was not emitted:

  1. $response->setCookie('foo', 'bar');
  2.  
  3. ob_start();
  4. $this->response->send();
  5. $output = ob_get_clean(); // in case you want to check the adtual body
  6.  
  7. $this->assertHeaderNotEmitted("Set-Cookie: banana");

Note: the test case with this should be run as a separate processin PHPunit.

assertCloseEnough($expected, $actual, $message=’’, $tolerance=1)

For extended execution time testing, tests that the absolute differencebetween expected and actual time is within the prescribed tolerance.:

  1. $timer = new Timer();
  2. $timer->start('longjohn', strtotime('-11 minutes'));
  3. $this->assertCloseEnough(11 * 60, $timer->getElapsedTime('longjohn'));

The above test will allow the actual time to be either 660 or 661 seconds.

assertCloseEnoughString($expected, $actual, $message=’’, $tolerance=1)

For extended execution time testing, tests that the absolute differencebetween expected and actual time, formatted as strings, is within the prescribed tolerance.:

  1. $timer = new Timer();
  2. $timer->start('longjohn', strtotime('-11 minutes'));
  3. $this->assertCloseEnoughString(11 * 60, $timer->getElapsedTime('longjohn'));

The above test will allow the actual time to be either 660 or 661 seconds.

Accessing Protected/Private Properties

When testing, you can use the following setter and getter methods to access protected and private methods andproperties in the classes that you are testing.

getPrivateMethodInvoker($instance, $method)

Enables you to call private methods from outside the class. This returns a function that can be called. The firstparameter is an instance of the class to test. The second parameter is the name of the method you want to call.

  1. // Create an instance of the class to test
  2. $obj = new Foo();
  3.  
  4. // Get the invoker for the 'privateMethod' method.
  5. $method = $this->getPrivateMethodInvoker($obj, 'privateMethod');
  6.  
  7. // Test the results
  8. $this->assertEquals('bar', $method('param1', 'param2'));

getPrivateProperty($instance, $property)

Retrieves the value of a private/protected class property from an instance of a class. The first parameter is aninstance of the class to test. The second parameter is the name of the property.

  1. // Create an instance of the class to test
  2. $obj = new Foo();
  3.  
  4. // Test the value
  5. $this->assertEquals('bar', $this->getPrivateProperty($obj, 'baz'));

setPrivateProperty($instance, $property, $value)

Set a protected value within a class instance. The first parameter is an instance of the class to test. The secondparameter is the name of the property to set the value of. The third parameter is the value to set it to:

  1. // Create an instance of the class to test
  2. $obj = new Foo();
  3.  
  4. // Set the value
  5. $this->setPrivateProperty($obj, 'baz', 'oops!');
  6.  
  7. // Do normal testing...

Mocking Services

You will often find that you need to mock one of the services defined in app/Config/Services.php to limityour tests to only the code in question, while simulating various responses from the services. This is especiallytrue when testing controllers and other integration testing. The Services class provides two methods to make thissimple: injectMock(), and reset().

injectMock()

This method allows you to define the exact instance that will be returned by the Services class. You can use this toset properties of a service so that it behaves in a certain way, or replace a service with a mocked class.

  1. public function testSomething()
  2. {
  3. $curlrequest = $this->getMockBuilder('CodeIgniter\HTTP\CURLRequest')
  4. ->setMethods(['request'])
  5. ->getMock();
  6. Services::injectMock('curlrequest', $curlrequest);
  7.  
  8. // Do normal testing here....
  9. }

The first parameter is the service that you are replacing. The name must match the function name in the Servicesclass exactly. The second parameter is the instance to replace it with.

reset()

Removes all mocked classes from the Services class, bringing it back to its original state.

Stream Filters

CITestStreamFilter provides an alternate to these helper methods.

You may need to test things that are difficult to test. Sometimes, capturing a stream, like PHP’s own STDOUT, or STDERR,might be helpful. The CITestStreamFilter helps you capture the output from the stream of your choice.

An example demonstrating this inside one of your test cases:

  1. public function setUp()
  2. {
  3. CITestStreamFilter::$buffer = '';
  4. $this->stream_filter = stream_filter_append(STDOUT, 'CITestStreamFilter');
  5. }
  6.  
  7. public function tearDown()
  8. {
  9. stream_filter_remove($this->stream_filter);
  10. }
  11.  
  12. public function testSomeOutput()
  13. {
  14. CLI::write('first.');
  15. $expected = "first.\n";
  16. $this->assertEquals($expected, CITestStreamFilter::$buffer);
  17. }