首页 > 解决方案 > 身份验证测试失败,使用 Laravel、phpunit 和 Homestead

问题描述

因此,我正在尝试在 Homestead 上运行的 Laravel 5.8 项目上测试注册和登录功能。

我的问题是我无法让测试(用于登录和注册)通过 assertAuthenticated() 和 assertAuthenticatedAs() 函数。

我使用创建了登录功能php artisan make:auth并且没有进行太多更改,只是创建了一个“用户名”字段来使用而不是电子邮件。

当我测试诸如 , 之类的东西assertStatus()$this->get(url),一切正常,但是当我添加$this->assertAuthenticatedAs($user)例如该行时,测试崩溃了。

这是我的实际传递函数:

    public function test_login_valid_user()
    {
        $user = factory(User::class)->create();

        $response = $this->post('/login', [
            'username' => $user->username,
            'password' => 'secret'
        ]);

        $response->assertStatus(302);

    }

如果我$this->assertAuthenticatedAs($user)在末尾添加该行,则会收到以下错误:

There was 1 failure:

1) Tests\Feature\Auth\LoginTest::test_login_valid_user
The current user is not authenticated.
Failed asserting that null is not null.

/home/vagrant/code/my_project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/Concerns/InteractsWithAuthentication.php:89
/home/vagrant/code/my_project/tests/Feature/Auth/LoginTest.php:39

我的注册测试也发生了同样的情况,在用户注册后,当我尝试检查时,$this->assertAuthenticated()我得到了同样的错误。

所以,我想到了与 Vagrant/Homestead 相关的会话问题,但我刚开始使用它们,找不到任何提示。而且我对 PHPUnit 和测试非常陌生,我才刚刚开始了解它是如何工作的。

标签: authenticationlaravel-5phpunithomestead

解决方案


问题与缓存有关。

首先phpunit.xml必须读取文件,因为您需要:<server name="APP_ENV" value="testing"/>

在测试之前使用命令

 php artisan config:clear

之后,您dump(config('app.env'));将成为testing(不是local)。

然后一切正常。


推荐阅读