Laravel:带身份验证的单元测试

Laravel: Unit testing with authentication

我正在尝试在我的 Laravel 应用程序中进行一些测试。首先,我正在检查登录是否正常:

public function testLogin(){

    $this->visit('/auth/login')
     ->type('mylogin', 'login')
     ->type('mypassword', 'password')
     ->press('Login')
     ->seePageIs('/home');
}

好的,登录正常! 现在,我想检查页面 /accountInfo 中的所有信息是否正确:

public function testAccountInfoDisplay(){
    $this->visit('/accountInfo')
        ->see('criticaldata');
}

但是我从来没有看到 /accountInfo 页面,因为我没有登录,所以被重定向了。

我在文档中看到了一些解决方案,例如:

$this->actingAs($user)
             ->withSession(['foo' => 'bar'])
             ->visit('/')
             ->see('Hello, '.$user->name);

但我无法伪造会话,因为当我登录时,我实际上是在向另一台服务器请求访问令牌以进行身份​​验证。没有这个令牌,我无法显示任何页面,因为数据服务器将拒绝连接。

简而言之,我在 testLogin 函数中得到了这个标记,但它在之后消失了。

我当然可以为每个测试进行登录,但是如果我有 150 个测试到 运行,那么请求就很多了。

是否有更好的方法在所有测试期间保留此令牌?

这是我所做的:

public function testLogin(){

    $this->visit('/auth/login')
     ->type('myLogin', 'login')
     ->type('myPassowrd', 'password')
     ->press('Login')
     ->seePageIs('/home');

     return Session::all();
}
/**
* @depends testLogin
*/
public function testAccountInfoDisplay($session){

    foreach($session as $key=>$value){
        Session::set($key, $value);
    }


    $this->visit('/accountInfo')
    ->see('4631');
}