1 <?xml version="1.0" encoding="UTF-8"?>
3 <sect2 id="zend.test.phpunit.testing">
4 <title>Testing your Controllers and MVC Applications</title>
7 Once you have your bootstrap in place, you can begin testing. Testing
8 is basically as you would expect in an PHPUnit test suite, with a few
13 First, you will need to dispatch a <acronym>URL</acronym> to test, using the
14 <methodname>dispatch()</methodname> method of the TestCase:
17 <programlisting language="php"><![CDATA[
18 class IndexControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
22 public function testHomePage()
31 There will be times, however, that you need to provide extra
32 information -- GET and POST variables, COOKIE information, etc. You can
33 populate the request with that information:
36 <programlisting language="php"><![CDATA[
37 class FooControllerTest extends Zend_Test_PHPUnit_ControllerTestCase
41 public function testBarActionShouldReceiveAllParameters()
44 $this->request->setQuery(array(
49 // Set POST variables:
50 $this->request->setPost(array(
55 // Set a cookie value:
56 $this->request->setCookie('user', 'matthew');
58 $this->request->setCookies(array(
59 'timestamp' => time(),
64 $this->request->setHeader('X-Requested-With', 'XmlHttpRequest');
66 // Set the request method:
67 $this->request->setMethod('POST');
70 $this->dispatch('/foo/bar');
78 Now that the request is made, it's time to start making assertions against it.
81 <sect3 id="zend.test.phpunit.testing.redirector">
82 <title>Controller Tests and the Redirector Action Helper</title>
86 The redirect action helper issues an <methodname>exit()</methodname> statement
87 when using the method <methodname>gotoAndExit()</methodname>
88 and will then obviously also stops a test running for this method.
89 For testability of your application dont use that method on the
95 Due to its nature the redirector action helper plugin issues a redirect
96 and exists after this. Because you cannot test parts of an application
97 that issue exit calls <classname>Zend_Test_PHPUnit_ControllerTestCase</classname>
98 automatically disables the exit part of the redirector which can cause
99 different behaviours in tests and the real application. To make sure
100 redirect work correctly you should it them in the following way:
103 <programlisting language="php"><![CDATA[
104 class MyController extends Zend_Controller_Action
106 public function indexAction()
108 if($someCondition == true) {
109 return $this->_redirect(...);
110 } else if($anotherCondition == true) {
111 $this->_redirector->gotoSimple("foo");
115 // do some stuff here
122 Depending on your application this is not enough as additional action,
123 <methodname>preDispatch()</methodname> or <methodname>postDispatch()</methodname>
124 logic might be executed. This cannot be handled in a good way with Zend Test