Unit Testing (PHPUnit): how to enter?

I am writing tests for my current project created using the Zend Framework. Everything is fine, but I have a problem with checking the registered actions of users / controllers: I need to log in to be able to perform the action / controller.

How can I log in to PHPUnit?

+4
source share
4 answers

As you say, you want to test actions / controllers, I suppose you are not typing unit tests, but functional / integration tests, i.e. working with Zend_Test and testing through MVC.

Here is the test function I used in the project where I am testing if the login is ok:

 public function testLoggingInShouldBeOk() { $this->dispatch('/login/login'); $csrf = $this->_getLoginFormCSRF(); $this->resetResponse(); $this->request->setPost(array( 'login' => 'LOGIN', 'password' => 'PASSWORD', 'csrfLogin' => $csrf, 'ok' => 'Login', )); $this->request->setMethod('POST'); $this->dispatch('/login/login'); $this->assertRedirectTo('/'); $this->assertTrue(Zend_Auth::getInstance()->hasIdentity()); } 

Simple: I download the login form, extract the CSRF token, filling out the form and posting it.

Then I can check if I am connected.


In doing so, you can probably extract the login part to call it before each of your tests, which requires a valid user to be registered.

+7
source

There is another way. On my User entity, I have a login() method that puts the user id into the session and a static variable. What I'm just doing in the setUp() test is calling $user->login() and it works. Sessions are not used in the test environment (setting Zend_Session::$isUnitTested = true has this effect), and the tests rely on a static variable. Just remember to clear the static variable ( logout() user) from tearDown() .

+1
source

I think this article can help you: http://perevodik.net/en/posts/7/ It describes how to create a fake identifier that you can use to set the environment to a state equivalent to the user logging in.

+1
source

Similarly, Pascal uses this function:

 $this->_getLoginFormCSRF(); 

I created a universal function that returns a value by loading a form using the form element manager:

public function _getCSRFHashValueFromForm ($ formAlias, $ csrfName) {$ form = $ this-> servicemanager-> get ('FormElementManager') → get ($ formAlias); return $ form-> get ($ csrfName) → getValue (); }

This, of course, assumes that CSRF is attached to the form, not inside any set of fields, etc.

0
source

All Articles