Laravel测试是否可以在同一测试中使用多个呼叫?

问题描述

我有这个测试:

public function test_user_can_access_the_application_page(  
{
        $user=[
            'email'=>'[email protected]','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中定义的内容)。

我认为该测试用例应具有自己的测试方法。我建议针对每个路由或每个用例使用一种测试方法。它可以使您的测试安排得井井有条,易于理解。

,

如果actingAs无法使用工厂,则应尝试使用cookie。

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

,

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

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

要回答您的问题,是的,您可以在同一测试中发出多个请求,但是在这种情况下,将登录测试链接到“应用程序/索引”页面可能没有多大意义。

public function test_the_user_can_login()
{
    $user = [
        'email'=>'[email protected]','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,"[email protected]")->first();

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

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

,

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