Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing (PHPUnit): how to login?

I'm writing tests for my current project, made with Zend Framework. Everything's fine, but I have a problem testing the logged users actions/controllers: I need to be logged in to be able to perform the action/controller.

How can I be logged in PHPUnit?

like image 899
OSdave Avatar asked Jan 22 '23 22:01

OSdave


1 Answers

As you are saying you want to test actions/controllers, I suppose you are not writting unit-tests, but functional/integration tests -- ie, working with Zend_Test and testing via the MVC.

Here is a test-function I used in a project, where I'm testing if logging in 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());
}

Simply : I'm loading the login form, extracting the CSRF token, populating the form, and posting it.

Then, I can test if I'm connected.


With that, you can probably extract the logging-in part, to call it before each one of your tests that require a valid user to be logged-in.

like image 193
Pascal MARTIN Avatar answered Jan 29 '23 06:01

Pascal MARTIN