Tester vos contrôleurs et vos applications MVC
Une fois , votre fichier d'amorçage en place, vous pouvez commencer à tester. Tester
est typiquement ce que vous auriez pu faire avec une suite de test PHPUnit ("test suite"),
avec quelques petites différences mineures.
Premièrement, vous devez distribuer l'URL à tester en utilisant la méthode
dispatch() de TestCase :
dispatch('/');
// ...
}
}
]]>
Il y a des moments, cependant, où vous devez fournir des informations supplémentaires
- des variables GET et POST, des informations de COOKIE, etc. Vous pouvez peupler la requête
avec ces informations :
request->setQuery(array(
'foo' => 'bar',
'bar' => 'baz',
));
// Passer les variables POST :
$this->request->setPost(array(
'baz' => 'bat',
'lame' => 'bogus',
));
// Paramètrer une valeur de cookie :
$this->request->setCookie('user', 'matthew');
// ou plusieurs :
$this->request->setCookies(array(
'timestamp' => time(),
'host' => 'foobar',
));
// Ajouter des en-têtes :
$this->request->setHeader('X-Requested-With', 'XmlHttpRequest');
// Définir le type de requête :
$this->request->setMethod('POST');
// Distribuer :
$this->dispatch('/foo/bar');
// ...
}
}
]]>
Maintenant que la requête est construite, il est temps de créer des assertions.
Controller Tests and the Redirector Action Helper
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:
_redirect(...);
} else if($anotherCondition == true) {
$this->_redirector->gotoSimple("foo");
return;
}
// do some stuff here
}
}
]]>
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.