Testing Controllers

Testing your controllers is made convenient with a couple of new helper classes and traits. When testing controllers,you can execute the code within a controller, without first running through the entire application bootstrap process.Often times, using the Feature Testing tools will be simpler, but this functionality is here incase you need it.

Note

Because the entire framework has not been bootstrapped, there will be times when you cannot test a controllerthis way.

The Helper Trait

You can use either of the base test classes, but you do need to use the ControllerTester traitwithin your tests:

  1. <?php namespace CodeIgniter;
  2.  
  3. use CodeIgniter\Test\ControllerTester;
  4.  
  5. class TestControllerA extends \CIDatabaseTestCase
  6. {
  7. use ControllerTester;
  8. }

Once the trait has been included, you can start setting up the environment, including the request and response classes,the request body, URI, and more. You specify the controller to use with the controller() method, passing in thefully qualified class name of your controller. Finally, call the execute() method with the name of the methodto run as the parameter:

  1. <?php namespace CodeIgniter;
  2.  
  3. use CodeIgniter\Test\ControllerTester;
  4.  
  5. class TestControllerA extends \CIDatabaseTestCase
  6. {
  7. use ControllerTester;
  8.  
  9. public function testShowCategories()
  10. {
  11. $result = $this->withURI('http://example.com/categories')
  12. ->controller(\App\Controllers\ForumController::class)
  13. ->execute('showCategories');
  14.  
  15. $this->assertTrue($result->isOK());
  16. }
  17. }

Helper Methods

controller($class)

Specifies the class name of the controller to test. The first parameter must be a fully qualified class name(i.e. include the namespace):

  1. $this->controller(\App\Controllers\ForumController::class);

execute($method)

Executes the specified method within the controller. The only parameter is the name of the method to run:

  1. $results = $this->controller(\App\Controllers\ForumController::class)
  2. ->execute('showCategories');

This returns a new helper class that provides a number of routines for checking the response itself. See belowfor details.

withConfig($config)

Allows you to pass in a modified version of ConfigApp.php to test with different settings:

  1. $config = new Config\App();
  2. $config->appTimezone = 'America/Chicago';
  3.  
  4. $results = $this->withConfig($config)
  5. ->controller(\App\Controllers\ForumController::class)
  6. ->execute('showCategories');

If you do not provide one, the application’s App config file will be used.

withRequest($request)

Allows you to provide an IncomingRequest instance tailored to your testing needs:

  1. $request = new CodeIgniter\HTTP\IncomingRequest(new Config\App(), new URI('http://example.com'));
  2. $request->setLocale($locale);
  3.  
  4. $results = $this->withRequest($request)
  5. ->controller(\App\Controllers\ForumController::class)
  6. ->execute('showCategories');

If you do not provide one, a new IncomingRequest instance with the default application values will be passedinto your controller.

withResponse($response)

Allows you to provide a Response instance:

  1. $response = new CodeIgniter\HTTP\Response(new Config\App());
  2.  
  3. $results = $this->withResponse($response)
  4. ->controller(\App\Controllers\ForumController::class)
  5. ->execute('showCategories');

If you do not provide one, a new Response instance with the default application values will be passedinto your controller.

withLogger($logger)

Allows you to provide a Logger instance:

  1. $logger = new CodeIgniter\Log\Handlers\FileHandler();
  2.  
  3. $results = $this->withResponse($response)
  4. -> withLogger($logger)
  5. ->controller(\App\Controllers\ForumController::class)
  6. ->execute('showCategories');

If you do not provide one, a new Logger instance with the default configuration values will be passedinto your controller.

withURI($uri)

Allows you to provide a new URI that simulates the URL the client was visiting when this controller was run.This is helpful if you need to check URI segments within your controller. The only parameter is a stringrepresenting a valid URI:

  1. $results = $this->withURI('http://example.com/forums/categories')
  2. ->controller(\App\Controllers\ForumController::class)
  3. ->execute('showCategories');

It is a good practice to always provide the URI during testing to avoid surprises.

withBody($body)

Allows you to provide a custom body for the request. This can be helpful when testing API controllers whereyou need to set a JSON value as the body. The only parameter is a string that represents the body of the request:

  1. $body = json_encode(['foo' => 'bar']);
  2.  
  3. $results = $this->withBody($body)
  4. ->controller(\App\Controllers\ForumController::class)
  5. ->execute('showCategories');

Checking the Response

When the controller is executed, a new ControllerResponse instance will be returned that provides a numberof helpful methods, as well as direct access to the Request and Response that were generated.

isOK()

This provides a simple check that the response would be considered a “successful” response. This primarily checks thatthe HTTP status code is within the 200 or 300 ranges:

  1. $results = $this->withBody($body)
  2. ->controller(\App\Controllers\ForumController::class)
  3. ->execute('showCategories');
  4.  
  5. if ($results->isOK())
  6. {
  7. . . .
  8. }

isRedirect()

Checks to see if the final response was a redirection of some sort:

  1. $results = $this->withBody($body)
  2. ->controller(\App\Controllers\ForumController::class)
  3. ->execute('showCategories');
  4.  
  5. if ($results->isRedirect())
  6. {
  7. . . .
  8. }

request()

You can access the Request object that was generated with this method:

  1. $results = $this->withBody($body)
  2. ->controller(\App\Controllers\ForumController::class)
  3. ->execute('showCategories');
  4.  
  5. $request = $results->request();

response()

This allows you access to the response object that was generated, if any:

  1. $results = $this->withBody($body)
  2. ->controller(\App\Controllers\ForumController::class)
  3. ->execute('showCategories');
  4.  
  5. $response = $results->response();

getBody()

You can access the body of the response that would have been sent to the client with the getBody() method. This couldbe generated HTML, or a JSON response, etc.:

  1. $results = $this->withBody($body)
  2. ->controller(\App\Controllers\ForumController::class)
  3. ->execute('showCategories');
  4.  
  5. $body = $results->getBody();

Response Helper methods

The response you get back contains a number of helper methods to inspect the HTML output within the response. Theseare useful for using within assertions in your tests.

The see() method checks the text on the page to see if it exists either by itself, or more specifically withina tag, as specified by type, class, or id:

  1. // Check that "Hello World" is on the page
  2. $results->see('Hello World');
  3. // Check that "Hello World" is within an h1 tag
  4. $results->see('Hello World', 'h1');
  5. // Check that "Hello World" is within an element with the "notice" class
  6. $results->see('Hello World', '.notice');
  7. // Check that "Hello World" is within an element with id of "title"
  8. $results->see('Hellow World', '#title');

The dontSee() method is the exact opposite:

  1. // Checks that "Hello World" does NOT exist on the page
  2. $results->dontSee('Hello World');
  3. // Checks that "Hellow World" does NOT exist within any h1 tag
  4. $results->dontSee('Hello World', 'h1');

The seeElement() and dontSeeElement() are very similar to the previous methods, but do not look at thevalues of the elements. Instead, they simply check that the elements exist on the page:

  1. // Check that an element with class 'notice' exists
  2. $results->seeElement('.notice');
  3. // Check that an element with id 'title' exists
  4. $results->seeElement('#title')
  5. // Verify that an element with id 'title' does NOT exist
  6. $results->dontSeeElement('#title');

You can use seeLink() to ensure that a link appears on the page with the specified text:

  1. // Check that a link exists with 'Upgrade Account' as the text::
  2. $results->seeLink('Upgrade Account');
  3. // Check that a link exists with 'Upgrade Account' as the text, AND a class of 'upsell'
  4. $results->seeLink('Upgrade Account', '.upsell');

The seeInField() method checks for any input tags exist with the name and value:

  1. // Check that an input exists named 'user' with the value 'John Snow'
  2. $results->seeInField('user', 'John Snow');
  3. // Check a multi-dimensional input
  4. $results->seeInField('user[name]', 'John Snow');

Finally, you can check if a checkbox exists and is checked with the seeCheckboxIsChecked() method:

  1. // Check if checkbox is checked with class of 'foo'
  2. $results->seeCheckboxIsChecked('.foo');
  3. // Check if checkbox with id of 'bar' is checked
  4. $results->seeCheckboxIsChecked('#bar');