因此,我正在尝试在 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 相关的 session 问题,但我刚刚开始使用它们并且找不到任何关于它的提示。我对 PHPUnit 和一般测试非常陌生,我才刚刚开始了解它是如何工作的。
最佳答案
问题与缓存有关。
首先文件phpunit.xml
必须阅读,因为您需要:<server name="APP_ENV" value="testing"/>
在您的测试使用命令之前
php artisan config:clear
之后您的
dump(config('app.env'));
将是 testing
(不是 local
)。然后一切正常。
关于authentication - 验证测试失败,使用 Laravel、phpunit 和 Homestead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55778430/