Iam a fan of 100% code coverage, but i have no idea how to test the ErrorController in Zend Framework.
It is no problem to test the 404Action and the errorAction:
public function testDispatchErrorAction()
{
$this->dispatch('/error/error');
$this->assertResponseCode(200);
$this->assertController('error');
$this->assertAction('error');
}
public function testDispatch404()
{
$this->dispatch('/error/errorxxxxx');
$this->assertResponseCode(404);
$this->assertController('error');
$this->assertAction('error');
}
But how to test for an application error (500)? maybe i need something like this?
public function testDispatch500()
{
throw new Exception('test');
$this->dispatch('/error/error');
$this->assertResponseCode(500);
$this->assertController('error');
$this->assertAction('error');
}
This is an old question but I was struggling with this today and couldn't find a good answer anywhere else so I'll go ahead and post what I did to solve this problem. The answer is actually really simple.
Point your dispatch to an action that will result in a thrown exception.
My application throws an error when a get request is made to a JSON end point, so I used one of those to test this.
/**
* @covers ErrorController::errorAction
*/
public function testErrorAction500() {
/**
* Requesting a page that doesn't exist returns the proper error message
*/
$this->dispatch('/my-json-controller/json-end-point');
$body = $this->getResponse()->getBody();
$this->assertResponseCode('500');
$this->assertContains('Application error',$body);
}
Alternatively, if you don't mind having an action just for testing, you could just create an action that only throws an error and point to that action in your unit test.
public function errorAction() {
throw new Exception('You should not be here');
}
Then your test would look like this:
/**
* @covers ErrorController::errorAction
*/
public function testErrorAction500() {
/**
* Requesting a page that doesn't exist returns the proper error message
*/
$this->dispatch('/my-error-controller/error');
$body = $this->getResponse()->getBody();
$this->assertResponseCode('500');
$this->assertContains('Application error',$body);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With