如何在单元测试中摆脱错误422 Laravel?

时间:2018-10-21 17:18:36

标签: testing laravel-5

所以我正在为laravel 5.7 Web应用程序编写单元测试,当我测试登录名时,它给我错误422(我知道它与无效数据有关,我只是不知道如何解决它)

public function testRegularUserLogin_CreatedRegularUse_ReturnsStoreView()
{
    $regularUser = factory( User::class)->create();

    $response = $this->json('POST','/login',
        [
            'email' => $regularUser->email,
            'password' => $regularUser->password,
            '_token' => csrf_token()
        ]);


    $response->assertStatus(200);


}

我尝试在标题上使用csrf令牌

This is the output that test gives me

1 个答案:

答案 0 :(得分:1)

您应该只模拟身份验证: 做这样的事情

public function getFakeClient()
{
    $client = factory(App\User::class)->create();
    $this->be($client);

    Auth::shouldReceive('user')->andReturn($this->client);
    Auth::shouldReceive('check')->andReturn(true);

    return $this->client;
}

然后

$user = $this->getFakeClient();
$user->shouldReceive('posts')->once()->andReturn(array('posts'));

由泰勒·奥特威尔(Taylor Otwell)本人here推荐。