Zend_Test_PHPUnit

Zend_Test_PHPUnit provides a TestCase for MVC applications that contains assertions for testing against a variety of responsibilities. Probably the easiest way to understand what it can do is to see an example.

Example #1 Application Login TestCase example

The following is a simple test case for a UserController to verify several things:

  • The login form should be displayed to non-authenticated users.

  • When a user logs in, they should be redirected to their profile page, and that profile page should show relevant information.

This particular example assumes a few things. First, we're moving most of our bootstrapping to a plugin. This simplifies setup of the test case as it allows us to specify our environment succinctly, and also allows us to bootstrap the application in a single line. Also, our particular example is assuming that autoloading is setup so we do not need to worry about requiring the appropriate classes (such as the correct controller, plugin, etc).

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     public function setUp()
  4.     {
  5.         $this->bootstrap = array($this, 'appBootstrap');
  6.         parent::setUp();
  7.     }
  8.  
  9.     public function appBootstrap()
  10.     {
  11.         $this->frontController
  12.              ->registerPlugin(new Bugapp_Plugin_Initialize('development'));
  13.     }
  14.  
  15.     public function testCallWithoutActionShouldPullFromIndexAction()
  16.     {
  17.         $this->dispatch('/user');
  18.         $this->assertController('user');
  19.         $this->assertAction('index');
  20.     }
  21.  
  22.     public function testIndexActionShouldContainLoginForm()
  23.     {
  24.         $this->dispatch('/user');
  25.         $this->assertAction('index');
  26.         $this->assertQueryCount('form#loginForm', 1);
  27.     }
  28.  
  29.     public function testValidLoginShouldGoToProfilePage()
  30.     {
  31.         $this->request->setMethod('POST')
  32.               ->setPost(array(
  33.                   'username' => 'foobar',
  34.                   'password' => 'foobar'
  35.               ));
  36.         $this->dispatch('/user/login');
  37.         $this->assertRedirectTo('/user/view');
  38.  
  39.         $this->resetRequest()
  40.              ->resetResponse();
  41.  
  42.         $this->request->setMethod('GET')
  43.              ->setPost(array());
  44.         $this->dispatch('/user/view');
  45.         $this->assertRoute('default');
  46.         $this->assertModule('default');
  47.         $this->assertController('user');
  48.         $this->assertAction('view');
  49.         $this->assertNotRedirect();
  50.         $this->assertQuery('dl');
  51.         $this->assertQueryContentContains('h2', 'User: foobar');
  52.     }
  53. }

This example could be written somewhat simpler -- not all the assertions shown are necessary, and are provided for illustration purposes only. Hopefully, it shows how simple it can be to test your applications.

Bootstrapping your TestCase

As noted in the Login example, all MVC test cases should extend Zend_Test_PHPUnit_ControllerTestCase. This class in turn extends PHPUnit_Framework_TestCase, and gives you all the structure and assertions you'd expect from PHPUnit -- as well as some scaffolding and assertions specific to Zend Framework's MVC implementation.

In order to test your MVC application, you will need to bootstrap it. There are several ways to do this, all of which hinge on the public $bootstrap property.

First, and probably most straight-forward, simply create a Zend_Application instance as you would in your index.php, and assign it to the $bootstrap property. Typically, you will do this in your setUp() method; you will need to call parent::setUp() when done:

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     public function setUp()
  4.     {
  5.         // Assign and instantiate in one step:
  6.         $this->bootstrap = new Zend_Application(
  7.             'testing',
  8.             APPLICATION_PATH . '/configs/application.ini'
  9.         );
  10.         parent::setUp();
  11.     }
  12. }

Second, you can set this property to point to a file. If you do this, the file should not dispatch the front controller, but merely setup the front controller and any application specific needs.

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     public $bootstrap = '/path/to/bootstrap/file.php'
  4.  
  5.     // ...
  6. }

Third, you can provide a PHP callback to execute in order to bootstrap your application. This method is seen in the Login example. If the callback is a function or static method, this could be set at the class level:

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     public $bootstrap = array('App', 'bootstrap');
  4.  
  5.     // ...
  6. }

In cases where an object instance is necessary, we recommend performing this in your setUp() method:

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     public function setUp()
  4.     {
  5.         // Use the 'start' method of a Bootstrap object instance:
  6.         $bootstrap = new Bootstrap('test');
  7.         $this->bootstrap = array($bootstrap, 'start');
  8.         parent::setUp();
  9.     }
  10. }

Note the call to parent::setUp(); this is necessary, as the setUp() method of Zend_Test_PHPUnit_ControllerTestCase will perform the remainder of the bootstrapping process (which includes calling the callback).

During normal operation, the setUp() method will bootstrap the application. This process first will include cleaning up the environment to a clean request state, resetting any plugins and helpers, resetting the front controller instance, and creating new request and response objects. Once this is done, it will then either include() the file specified in $bootstrap, or call the callback specified.

Bootstrapping should be as close as possible to how the application will be bootstrapped. However, there are several caveats:

  • Do not provide alternate implementations of the Request and Response objects; they will not be used. Zend_Test_PHPUnit_ControllerTestCase uses custom request and response objects, Zend_Controller_Request_HttpTestCase and Zend_Controller_Response_HttpTestCase, respectively. These objects provide methods for setting up the request environment in targeted ways, and pulling response artifacts in specific ways.

  • Do not expect to test server specifics. In other words, the tests are not a guarantee that the code will run on a specific server configuration, but merely that the application should run as expected should the router be able to route the given request. To this end, do not set server-specific headers in the request object.

Once the application is bootstrapped, you can then start creating your tests.

Testing your Controllers and MVC Applications

Once you have your bootstrap in place, you can begin testing. Testing is basically as you would expect in an PHPUnit test suite, with a few minor differences.

First, you will need to dispatch a URL to test, using the dispatch() method of the TestCase:

  1. class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     // ...
  4.  
  5.     public function testHomePage()
  6.     {
  7.         $this->dispatch('/');
  8.         // ...
  9.     }
  10. }

There will be times, however, that you need to provide extra information -- GET and POST variables, COOKIE information, etc. You can populate the request with that information:

  1. class FooControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     // ...
  4.  
  5.     public function testBarActionShouldReceiveAllParameters()
  6.     {
  7.         // Set GET variables:
  8.         $this->request->setQuery(array(
  9.             'foo' => 'bar',
  10.             'bar' => 'baz',
  11.         ));
  12.  
  13.         // Set POST variables:
  14.         $this->request->setPost(array(
  15.             'baz'  => 'bat',
  16.             'lame' => 'bogus',
  17.         ));
  18.  
  19.         // Set a cookie value:
  20.         $this->request->setCookie('user', 'matthew');
  21.         // or many:
  22.         $this->request->setCookies(array(
  23.             'timestamp' => time(),
  24.             'host'      => 'foobar',
  25.         ));
  26.  
  27.         // Set headers, even:
  28.         $this->request->setHeader('X-Requested-With', 'XmlHttpRequest');
  29.  
  30.         // Set the request method:
  31.         $this->request->setMethod('POST');
  32.  
  33.         // Dispatch:
  34.         $this->dispatch('/foo/bar');
  35.  
  36.         // ...
  37.     }
  38. }

Now that the request is made, it's time to start making assertions against it.

Controller Tests and the Redirector Action Helper

Important

The redirect action helper issues an exit() statement when using the method gotoAndExit() and will then obviously also stops a test running for this method. For testability of your application dont use that method on the redirector!

Due to its nature the redirector action helper plugin issues a redirect and exists after this. Because you cannot test parts of an application that issue exit calls Zend_Test_PHPUnit_ControllerTestCase automatically disables the exit part of the redirector which can cause different behaviours in tests and the real application. To make sure redirect work correctly you should it them in the following way:

  1. class MyController extends Zend_Controller_Action
  2. {
  3.     public function indexAction()
  4.     {
  5.         if($someCondition == true) {
  6.             return $this->_redirect(...);
  7.         } else if($anotherCondition == true) {
  8.             $this->_redirector->gotoSimple("foo");
  9.             return;
  10.         }
  11.  
  12.         // do some stuff here
  13.     }
  14. }
Important

Depending on your application this is not enough as additional action, preDispatch() or postDispatch() logic might be executed. This cannot be handled in a good way with Zend Test currently.

Assertions

Assertions are at the heart of Unit Testing; you use them to verify that the results are what you expect. To this end, Zend_Test_PHPUnit_ControllerTestCase provides a number of assertions to make testing your MVC apps and controllers simpler.

CSS Selector Assertions

CSS selectors are an easy way to verify that certain artifacts are present in the response content. They also make it trivial to ensure that items necessary for Javascript UIs and/or AJAX integration will be present; most JS toolkits provide some mechanism for pulling DOM elements based on CSS selectors, so the syntax would be the same.

This functionality is provided via Zend_Dom_Query, and integrated into a set of 'Query' assertions. Each of these assertions takes as their first argument a CSS selector, with optionally additional arguments and/or an error message, based on the assertion type. You can find the rules for writing the CSS selectors in the Zend_Dom_Query theory of operation chapter. Query assertions include:

  • assertQuery($path, $message = ''): assert that one or more DOM elements matching the given CSS selector are present. If a $message is present, it will be prepended to any failed assertion message.

  • assertQueryContentContains($path, $match, $message = ''): assert that one or more DOM elements matching the given CSS selector are present, and that at least one contains the content provided in $match. If a $message is present, it will be prepended to any failed assertion message.

  • assertQueryContentRegex($path, $pattern, $message = ''): assert that one or more DOM elements matching the given CSS selector are present, and that at least one matches the regular expression provided in $pattern. If a $message is present, it will be prepended to any failed assertion message.

  • assertQueryCount($path, $count, $message = ''): assert that there are exactly $count DOM elements matching the given CSS selector present. If a $message is present, it will be prepended to any failed assertion message.

  • assertQueryCountMin($path, $count, $message = ''): assert that there are at least $count DOM elements matching the given CSS selector present. If a $message is present, it will be prepended to any failed assertion message. Note: specifying a value of 1 for $count is the same as simply using assertQuery().

  • assertQueryCountMax($path, $count, $message = ''): assert that there are no more than $count DOM elements matching the given CSS selector present. If a $message is present, it will be prepended to any failed assertion message. Note: specifying a value of 1 for $count is the same as simply using assertQuery().

Additionally, each of the above has a 'Not' variant that provides a negative assertion: assertNotQuery(), assertNotQueryContentContains(), assertNotQueryContentRegex(), and assertNotQueryCount(). (Note that the min and max counts do not have these variants, for what should be obvious reasons.)

XPath Assertions

Some developers are more familiar with XPath than with CSS selectors, and thus XPath variants of all the Query assertions are also provided. These are:

  • assertXpath($path, $message = '')

  • assertNotXpath($path, $message = '')

  • assertXpathContentContains($path, $match, $message = '')

  • assertNotXpathContentContains($path, $match, $message = '')

  • assertXpathContentRegex($path, $pattern, $message = '')

  • assertNotXpathContentRegex($path, $pattern, $message = '')

  • assertXpathCount($path, $count, $message = '')

  • assertNotXpathCount($path, $count, $message = '')

  • assertXpathCountMin($path, $count, $message = '')

  • assertNotXpathCountMax($path, $count, $message = '')

Redirect Assertions

Often an action will redirect. Instead of following the redirect, Zend_Test_PHPUnit_ControllerTestCase allows you to test for redirects with a handful of assertions.

  • assertRedirect($message = ''): assert simply that a redirect has occurred.

  • assertNotRedirect($message = ''): assert that no redirect has occurred.

  • assertRedirectTo($url, $message = ''): assert that a redirect has occurred, and that the value of the Location header is the $url provided.

  • assertNotRedirectTo($url, $message = ''): assert that a redirect has either NOT occurred, or that the value of the Location header is NOT the $url provided.

  • assertRedirectRegex($pattern, $message = ''): assert that a redirect has occurred, and that the value of the Location header matches the regular expression provided by $pattern.

  • assertNotRedirectRegex($pattern, $message = ''): assert that a redirect has either NOT occurred, or that the value of the Location header does NOT match the regular expression provided by $pattern.

Response Header Assertions

In addition to checking for redirect headers, you will often need to check for specific HTTP response codes and headers -- for instance, to determine whether an action results in a 404 or 500 response, or to ensure that JSON responses contain the appropriate Content-Type header. The following assertions are available.

  • assertResponseCode($code, $message = ''): assert that the response resulted in the given HTTP response code.

  • assertHeader($header, $message = ''): assert that the response contains the given header.

  • assertHeaderContains($header, $match, $message = ''): assert that the response contains the given header and that its content contains the given string.

  • assertHeaderRegex($header, $pattern, $message = ''): assert that the response contains the given header and that its content matches the given regex.

Additionally, each of the above assertions have a 'Not' variant for negative assertions.

Request Assertions

It's often useful to assert against the last run action, controller, and module; additionally, you may want to assert against the route that was matched. The following assertions can help you in this regard:

  • assertModule($module, $message = ''): Assert that the given module was used in the last dispatched action.

  • assertController($controller, $message = ''): Assert that the given controller was selected in the last dispatched action.

  • assertAction($action, $message = ''): Assert that the given action was last dispatched.

  • assertRoute($route, $message = ''): Assert that the given named route was matched by the router.

Each also has a 'Not' variant for negative assertions.

Examples

Knowing how to setup your testing infrastructure and how to make assertions is only half the battle; now it's time to start looking at some actual testing scenarios to see how you can leverage them.

Example #2 Testing a UserController

Let's consider a standard task for a website: authenticating and registering users. In our example, we'll define a UserController for handling this, and have the following requirements:

  • If a user is not authenticated, they will always be redirected to the login page of the controller, regardless of the action specified.

  • The login form page will show both the login form and the registration form.

  • Providing invalid credentials should result in returning to the login form.

  • Valid credentials should result in redirecting to the user profile page.

  • The profile page should be customized to contain the user's username.

  • Authenticated users who visit the login page should be redirected to their profile page.

  • On logout, a user should be redirected to the login page.

  • With invalid data, registration should fail.

We could, and should define further tests, but these will do for now.

For our application, we will define a plugin, 'Initialize', that runs at routeStartup(). This allows us to encapsulate our bootstrap in an OOP interface, which also provides an easy way to provide a callback. Let's look at the basics of this class first:

  1. class Bugapp_Plugin_Initialize extends Zend_Controller_Plugin_Abstract
  2. {
  3.     /**
  4.      * @var Zend_Config
  5.      */
  6.     protected static $_config;
  7.  
  8.     /**
  9.      * @var string Current environment
  10.      */
  11.     protected $_env;
  12.  
  13.     /**
  14.      * @var Zend_Controller_Front
  15.      */
  16.     protected $_front;
  17.  
  18.     /**
  19.      * @var string Path to application root
  20.      */
  21.     protected $_root;
  22.  
  23.     /**
  24.      * Constructor
  25.      *
  26.      * Initialize environment, root path, and configuration.
  27.      *
  28.      * @param  string $env
  29.      * @param  string|null $root
  30.      * @return void
  31.      */
  32.     public function __construct($env, $root = null)
  33.     {
  34.         $this->_setEnv($env);
  35.         if (null === $root) {
  36.             $root = realpath(dirname(__FILE__) . '/../../../');
  37.         }
  38.         $this->_root = $root;
  39.  
  40.         $this->initPhpConfig();
  41.  
  42.         $this->_front = Zend_Controller_Front::getInstance();
  43.     }
  44.  
  45.     /**
  46.      * Route startup
  47.      *
  48.      * @return void
  49.      */
  50.     public function routeStartup(Zend_Controller_Request_Abstract $request)
  51.     {
  52.         $this->initDb();
  53.         $this->initHelpers();
  54.         $this->initView();
  55.         $this->initPlugins();
  56.         $this->initRoutes();
  57.         $this->initControllers();
  58.     }
  59.  
  60.     // definition of methods would follow...
  61. }

This allows us to create a bootstrap callback like the following:

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     public function appBootstrap()
  4.     {
  5.         $controller = $this->getFrontController();
  6.         $controller->registerPlugin(
  7.             new Bugapp_Plugin_Initialize('development')
  8.         );
  9.     }
  10.  
  11.     public function setUp()
  12.     {
  13.         $this->bootstrap = array($this, 'appBootstrap');
  14.         parent::setUp();
  15.     }
  16.  
  17.     // ...
  18. }

Once we have that in place, we can write our tests. However, what about those tests that require a user is logged in? The easy solution is to use our application logic to do so... and fudge a little by using the resetRequest() and resetResponse() methods, which will allow us to dispatch another request.

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     // ...
  4.  
  5.     public function loginUser($user, $password)
  6.     {
  7.         $this->request->setMethod('POST')
  8.                       ->setPost(array(
  9.                           'username' => $user,
  10.                           'password' => $password,
  11.                       ));
  12.         $this->dispatch('/user/login');
  13.         $this->assertRedirectTo('/user/view');
  14.  
  15.         $this->resetRequest()
  16.              ->resetResponse();
  17.  
  18.         $this->request->setPost(array());
  19.  
  20.         // ...
  21.     }
  22.  
  23.     // ...
  24. }

Now let's write tests:

  1. class UserControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
  2. {
  3.     // ...
  4.  
  5.     public function testCallWithoutActionShouldPullFromIndexAction()
  6.     {
  7.         $this->dispatch('/user');
  8.         $this->assertController('user');
  9.         $this->assertAction('index');
  10.     }
  11.  
  12.     public function testLoginFormShouldContainLoginAndRegistrationForms()
  13.     {
  14.         $this->dispatch('/user');
  15.         $this->assertQueryCount('form', 2);
  16.     }
  17.  
  18.     public function testInvalidCredentialsShouldResultInRedisplayOfLoginForm()
  19.     {
  20.         $request = $this->getRequest();
  21.         $request->setMethod('POST')
  22.                 ->setPost(array(
  23.                     'username' => 'bogus',
  24.                     'password' => 'reallyReallyBogus',
  25.                 ));
  26.         $this->dispatch('/user/login');
  27.         $this->assertNotRedirect();
  28.         $this->assertQuery('form');
  29.     }
  30.  
  31.     public function testValidLoginShouldRedirectToProfilePage()
  32.     {
  33.         $this->loginUser('foobar', 'foobar');
  34.     }
  35.  
  36.     public function testAuthenticatedUserShouldHaveCustomizedProfilePage()
  37.     {
  38.         $this->loginUser('foobar', 'foobar');
  39.         $this->request->setMethod('GET');
  40.         $this->dispatch('/user/view');
  41.         $this->assertNotRedirect();
  42.         $this->assertQueryContentContains('h2', 'foobar');
  43.     }
  44.  
  45.     public function
  46.         testAuthenticatedUsersShouldBeRedirectedToProfileWhenVisitingLogin()
  47.     {
  48.         $this->loginUser('foobar', 'foobar');
  49.         $this->request->setMethod('GET');
  50.         $this->dispatch('/user');
  51.         $this->assertRedirectTo('/user/view');
  52.     }
  53.  
  54.     public function testUserShouldRedirectToLoginPageOnLogout()
  55.     {
  56.         $this->loginUser('foobar', 'foobar');
  57.         $this->request->setMethod('GET');
  58.         $this->dispatch('/user/logout');
  59.         $this->assertRedirectTo('/user');
  60.     }
  61.  
  62.     public function testRegistrationShouldFailWithInvalidData()
  63.     {
  64.         $data = array(
  65.             'username' => 'This will not work',
  66.             'email'    => 'this is an invalid email',
  67.             'password' => 'Th1s!s!nv@l1d',
  68.             'passwordVerification' => 'wrong!',
  69.         );
  70.         $request = $this->getRequest();
  71.         $request->setMethod('POST')
  72.                 ->setPost($data);
  73.         $this->dispatch('/user/register');
  74.         $this->assertNotRedirect();
  75.         $this->assertQuery('form .errors');
  76.     }
  77. }

Notice that these are terse, and, for the most part, don't look for actual content. Instead, they look for artifacts within the response -- response codes and headers, and DOM nodes. This allows you to verify that the structure is as expected -- preventing your tests from choking every time new content is added to the site.

Also notice that we use the structure of the document in our tests. For instance, in the final test, we look for a form that has a node with the class of "errors"; this allows us to test merely for the presence of form validation errors, and not worry about what specific errors might have been thrown.

This application may utilize a database. If so, you will probably need some scaffolding to ensure that the database is in a pristine, testable configuration at the beginning of each test. PHPUnit already provides functionality for doing so; » read about it in the PHPUnit documentation. We recommend using a separate database for testing versus production, and in particular recommend using either a SQLite file or in-memory database, as both options perform very well, do not require a separate server, and can utilize most SQL syntax.

blog comments powered by Disqus