测试检查用户登录 laravel
test check user logged in laravel
我有一条简单的功能路径:
if (Auth::check()) {
return response()->json('true');
} else {
return response()->json('false');
}
我需要使用 PHPUnit 中的类似内容来测试此功能:
$this->get('auth/checkLoggedIn')
->seeJson([true]);
如何模拟测试用户登录?
使用actngAs($user_id)
模拟登录用户。
更完整的示例:
// simulate ajax request
$this->actingAs($user_id)
->post(route('api.bookmark.store'), [
'event' => $this->event->id,
'_token' => csrf_token()
]);
Return 响应是这样的:
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]);
}
我有一条简单的功能路径:
if (Auth::check()) {
return response()->json('true');
} else {
return response()->json('false');
}
我需要使用 PHPUnit 中的类似内容来测试此功能:
$this->get('auth/checkLoggedIn')
->seeJson([true]);
如何模拟测试用户登录?
使用actngAs($user_id)
模拟登录用户。
更完整的示例:
// simulate ajax request
$this->actingAs($user_id)
->post(route('api.bookmark.store'), [
'event' => $this->event->id,
'_token' => csrf_token()
]);
Return 响应是这样的:
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]);
}