我有一个简单的功能途径:
if (Auth::check()) {
return response()->json('true');
} else {
return response()->json('false');
}
我需要使用 PHPUnit 中的类似内容来测试此函数:
$this->get('auth/checkLoggedIn')
->seeJson([true]);
如何模拟测试用户已登录?
最佳答案
返回类似这样的响应:
if (Auth::check()) {
return response()->json(["logged"=>true]);
} else {
return response()->json(["logged"=>false]);
}
使用laravel的工厂模型,创建一个示例用户。为了避免 TokenMismatch 错误,您可以使用 WithoutMiddleware 特征。但如果它是 GET
请求,则不需要它。但如果它是一个 POST
那么你可能需要它。
所以你可以使用其中之一
use Illuminate\Foundation\Testing\WithoutMiddleware;
UserTest extends TestCase {
use WithoutMiddleware;
/**
*@test
*/
public function it_tests_authentication()
{
$user = factory(User::class)->create();
$this->actingAs($user);
$this->post('auth/checkLoggedIn')
->seeJson(["logged"=>true]);
//or GET depending on your route
$this->get('auth/checkLoggedIn')
->seeJson(["logged"=>true]);
}
关于laravel - 测试检查用户是否已登录 laravel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35209162/