1

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());
}
Ron
  • 22,128
  • 31
  • 108
  • 206
  • Procide the code you tested ;) (even if i wont be able to help, other may seeing your tests) – Sam Jan 10 '13 at 15:29
  • as i said, its a very simple test by now. i just need to bypass the auth for the tester... and for this problem i dont have any code ;) – Ron Jan 10 '13 at 15:31
  • What do you want to test? That your `add` action can be done **when authenticated**? Then you have to mock the authentication service and put an identity in there so you can test your controller accepts the valid auth. Just to be sure: test also the case where the unauthorized request causes a redirect you have now. – Jurian Sluiman Jan 10 '13 at 18:01
  • thanks, good idea! is there an easy way to mock the auth? – Ron Jan 11 '13 at 07:42

1 Answers1

3
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.

Daniel M
  • 3,369
  • 20
  • 30
  • sorry for this dumb question but how to i create the connection between the `$authMock` and my function to call? an example would be great! – Ron Jan 11 '13 at 10:39
  • 2
    @Ron not dumb question. see http://www.afewmorelines.com/mocking-user-identities-in-zf2-action-controller-unit-tests/ if you use serviceLocator to get AuthenticationService. – imel96 Nov 27 '13 at 06:30