0

I'm trying to unit test a ZF2 application. I have a form that changes slightly depending on whether it's for students or employees, and I have two separate factories for producing them.

Anyway, I tried testing the student form in the following test:

public function testStudentFormAcceptsValidValues()
{
    $this->getEmMock();
    $this->mockLogin('admin');

    $form = $this->serviceManager->get('student_form');
    $this->getApplicationServiceLocator()->setService('student_form', $form);
    $url = '/user/account/add/student';
    $this->dispatch($url);
    $csrf = $form->get('csrf')->getValue();

    $postData = $this->userStubData[1];
    $postData['csrf'] = $csrf;
    $user = new UserEntity();

    $this->getApplicationServiceLocator()->setService('user_entity', $user);

    $this->dispatch($url, 'POST', $postData);

    $this->assertRedirectTo('/user#students');
    $this->assertEntityPropertiesSet($user, $postData);
}

When I run this test, it passes. However, I was doing a similar test for an employee form, but it would fail because the CSRF token was wrong. So just for kicks, I decided to run the above test twice in a row to see what would happen. It failed again, and for the exact same reason.

I finally decided to check the CSRF token values for the two tests, and I found that they were both the same. For some reason, the form was re-using the CSRF value from the previous test instead of creating a new one, and the form was rejecting it as a result.

What do I have to do in order to clear out the old CSRF value and get a new one that the form will accept?

blainarmstrong
  • 1,040
  • 1
  • 13
  • 33

1 Answers1

0

I don't know exactly how you configured your testing but it is common to bootstrap the application between tests so that you run the second test with all services etc reinitialized.

Probably some of your services are initialized in the first test and the second test reuses the already initialized service with the "wrong" old values from the first test.

Wilt
  • 41,477
  • 12
  • 152
  • 203
  • That's basically the bootstrap file that I use for my tests. I don't have a tearDown method written though--is there anything I can put in it to clear out stuff like that? – blainarmstrong Feb 11 '15 at 13:40