Question

I want to create a simple access unit test like it is shown in the tutorial.

My project uses ZFCUser for authentication.

As a result my (obviously not authenticated) tester get a HTTP response of 302 and not the expected 200.

Any ideas what I can do about it? Thanks!

The code from the tutorial looks like this:

public function testAddActionCanBeAccessed()
{
    $this->routeMatch->setParam('action', 'add');

    $result   = $this->controller->dispatch($this->request);
    $response = $this->controller->getResponse();

    $this->assertEquals(200, $response->getStatusCode());
}
Was it helpful?

Solution

thanks, good idea! is there an easy way to mock the auth? – Ron

I'm posting this as an answer, because its too much to press it into a comment. Yes, there is an easy way to mock the AuthenticationService class. First of all, check the docs on Stubs / Mocks.

What you need to do is to create the mock from Zend\Authentication\AuthenticationService and configure it to pretend to contain an identity.

public function testSomethingThatRequiresAuth()
{
    $authMock = $this->getMock('Zend\Authentication\AuthenticationService');
    $authMock->expects($this->any())
             ->method('hasIdentity')
             ->will($this->returnValue(true));

    $authMock->expects($this->any())
             ->method('getIdentity')
             ->will($this->returnValue($identityMock));

    // Assign $authMock to the part where Authentication is required.
}

In this example, a variable $identityMock is required to be defined previously. It could be a mock of your user model class or something like that.

Note that I haven't tested it, so it might not work instantly. However, its just supposed to show you the direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top