authentication - 身份验证测试失败,使用 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 和测试非常陌生,我才刚刚开始了解它是如何工作的。
解决方案
问题与缓存有关。
首先phpunit.xml
必须读取文件,因为您需要:<server name="APP_ENV" value="testing"/>
在测试之前使用命令
php artisan config:clear
之后,您dump(config('app.env'));
将成为testing
(不是local
)。
然后一切正常。
推荐阅读
- python-3.x - 与另一个线程或进程共享 asyncio.Queue
- azure - 使用 Terraform 部署期间在 Azure VM 上安装 DSC 扩展的问题
- c# - 如何将 JSON 中的键值对更改为 XML 属性而不是节点
- python - 用 Python 连接 Lifx 灯
- vb.net - 从文本文件中选择随机人并更改相应的值
- postgresql - 如何在 jmeter 中通过隧道配置 PostgreSQL 数据库
- javascript - 使用 javascript 在 php 循环上构建,类只记录第一个结果
- python - 查找两个标签之间的有效日期
- java - Java 无法映射本机库
- java - Spring缓存不适用于子类中的覆盖方法