Laravel 测试。可以在同一测试中使用多个调用吗?

Laravel testing. Is possible to use multiple calls in same test?

我有这个测试:

public function test_user_can_access_the_application_page(  
{
        $user=[
            'email'=>'user@user.com',
            'password'=>'user1234',
        ];

        $response=$this->call('POST','/login',$user);
        $this->assertAuthenticated();
        $response->assertStatus(302)
            ->assertRedirect('/dashboard')
            ->assertLocation('/dashboard');
        $response=$this->call('GET','/application/index');
        $response->assertLocation('/application/index');
}

我登录后,它会将我定向到仪表板,直到现在还可以,但是如果我想在那之后访问其他页面,我不能。出现此错误。

预期:'http://mock.test/application/index'

实际:'http://mock.test'

同一个测试不能多次调用吗,还是登录后可以通过其他方式访问其他页面? (注意:actingAs 不能使用工厂,所以我需要登录)。

我想您需要以用户身份调用该函数,因为您只能在登录后访问它。Laravel 为这种情况提供了 actingAs() 方法。

https://laravel.com/docs/7.x/http-tests#session-and-authentication

您可以创建一个随机用户,该用户有权登录您的应用程序或获取种子用户并调用函数作为所选用户。

$response=$this->actingAs($user)->call('GET','/application/index');

如果您在没有 actingAs() 的情况下调用它,您的中间件会将您重定向回登录或主屏幕(您在 LoginController 中定义的内容)。

在我看来,这个测试用例应该有自己的测试方法。我建议对每个路由或每个用例使用一种测试方法。它使您的测试安排清晰且易于理解。

如果要进行身份验证,最简单的方法是让 PHPUnit 使用 actingAs() 方法模拟身份验证。

此方法使用户通过身份验证,因此您不想用它来测试登录方法。您应该将登录测试与测试其他页面分开编写。

回答你的问题,是的,你可以在同一个测试中发出多个请求,但在这种情况下,将登录测试链接到 'application/index' 页面可能没有多大意义。

public function test_the_user_can_login()
{
    $user = [
        'email'=>'user@user.com',
        'password'=>'user1234',
    ];

    $response = $this->call('POST','/login',$user);
    $this->assertAuthenticated();
    $response->assertStatus(302)
             ->assertRedirect('/dashboard')
             ->assertLocation('/dashboard');
}

public function test_user_can_access_the_application_page()
{
    $user = User::where($email, "user@user.com")->first();

    $response = $this->actingAs($user)
                     ->call('GET','/application/index');

    $response->assertLocation('/application/index');
}

如果您不能为 actingAs 使用工厂,那么您应该尝试使用 cookie。

查看 https://github.com/firebase/php-jwt 库。

我在laravel 8中经历过,我使用评论@test并参与了第二次测试!我的意思是,如果你使用两个函数进行测试,你必须使用@test php artisan test,测试它们。