2

I've just started with php unit. In my test cases UsersController should return:

public function UsersController() {
    ....
    throw new \Cake\Network\Exception\NotFoundException();
}

phpunit code

$this->setExpectedException('Cake\Network\Exception\NotFoundException');

returns an assertion failed that looks like:

App\Test\TestCase\Controller\UsersControllerTest::testActivate Failed asserting that exception of type "Cake\Network\Exception\NotFoundException" is thrown.

Meanwhile browser return a 404 PageNotFound and $this->assertResponseOk() returns:

App\Test\TestCase\Controller\UsersControllerTest::testActivate exception 'Cake\Network\Exception\NotFoundException' with message 'Not Found' in /vagrant/ifmx.local/src/Controller/UsersController.php:215

Does somebody know why it's happened? And is there any way to get exception message in unit test.

1
  • return throw? That's a parser error right there... Commented Jan 15, 2016 at 16:02

1 Answer 1

0

You seem to have misunderstood how the integration test case works.

It doesn't just wrap a call to a controller method, like $controller->action(), it simulates a whole request, and as such, exceptions are being catched, and result in error pages being rendered, just like it happens when you are visiting a URL in your browser.

So PHPUnit will never know about the exception, and thus you cannot use the expected exception feature as you would when directly testing specific code parts where exceptions bubble up to PHPUnit. If that would happen, then it wouldn't be possible to assert responses, which one might want to do, even when an exception has been thrown.

Possible exceptions are being buffered in the IntegrationTestCase::$_exception property, which you can for example use to test if, what kind of exception has been thrown, etc, like

$this->assertInstanceOf('\Cake\Network\Exception\NotFoundException', $this->_exception);
$this->assertEquals('Not Found', $this->_exception->getMessage());
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, You are right. I've tried to use TestCases not correctly. Thanks a lot

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.