Hector Virgen <djvirgen@gmail.com> writes:
> I am unit testing my controllers using Zend_Test and am having trouble
> testing exceptions thrown by action methods. Here's my test:
>
> /**
> * @expectedException My_Exception
> public function testExpectedException()
> {
> $this->dispatch('page/that/should/throw/exception');
> }
I know it's customary for controller unit tests to use the dispatch
method, but I think using dispatch goes against writing a unit test.
When you use dispatch, you're writing more of an integration test
because you end up running though your whole application stack, from
bootstrap to front controller and view initialization to finally your
controller.
If you would like to test that this exception is being thrown, perhaps
isolate your controller and treat it like a simple object
/**
* @expectedException My_Exception
*/
public function testExpectedException()
{
$controller = new YourController(
// You could also use PHPUnit mocks here
new Zend_Controller_Request_HttpTestCase(),
new Zend_Controller_Response_HttpTestCase()
);
$controller->exceptionAction();
}
> I've tried disabling the error handler plugin:
> $front->setParam('noErrorHandler', true);
>
> I've also tried enabling throwExceptions in the front controller:
> $front->throwExceptions(true);
>
> But it seems no matter what I do the exception is caught by the front
> controller and attached to the response object (and not rethrown).
>
> Technically, I could write my test like this:
>
> public function testExpectedException()
> {
> $this->dispatch('page/that/should/throw/exception');
> if (!$this->response->isException()) {
> $this->fail('expecting an exception!');
> }
> }
If you check Zend_Test_PHPUnit_ControllerTestCase.php, you will see that
in the dispatch method there (as I am assuming that you're using this
method and that your test cases extend from this) that said method sets
throwExceptions to true. That appears to be why your settings aren't sticking.
Cheers,
- K. Adam Christensen
没有评论:
发表评论