Zend_Test_PHPUnitZend_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:
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).
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 TestCaseAs 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:
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.
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:
In cases where an object instance is necessary, we recommend performing this in your setUp() method:
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:
Once the application is bootstrapped, you can then start creating your tests. Testing your Controllers and MVC ApplicationsOnce 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:
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:
Now that the request is made, it's time to start making assertions against it. Controller Tests and the Redirector Action HelperImportant
The redirect action helper issues an exit() statement when using the method gotoAndExit() and will then obviously also stop any tests running against controllers using this method. For testability of your application dont use that method of the redirector! Due to its nature the redirector action helper plugin issues a redirect and then exits. Because you cannot test parts of an application that issue exit calls Zend_Test_PHPUnit_ControllerTestCase automatically disables the exit part of the redirector as it can cause test behavior to differ from the real application. To ensure your controllers can be properly tested, please make use of the redirector when you need to redirect the user to a different page:
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. AssertionsAssertions 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 AssertionsCSS 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:
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 AssertionsSome developers are more familiar with XPath than with CSS selectors, and thus XPath variants of all the Query assertions are also provided. These are:
Redirect AssertionsOften an action will redirect. Instead of following the redirect, Zend_Test_PHPUnit_ControllerTestCase allows you to test for redirects with a handful of assertions.
Response Header AssertionsIn 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.
Additionally, each of the above assertions have a 'Not' variant for negative assertions. Request AssertionsIt'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:
Each also has a 'Not' variant for negative assertions. ExamplesKnowing 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:
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:
This allows us to create a bootstrap callback like the following:
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.
Now let's write tests:
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.
|