测试检查用户登录laravel

时间:2016-02-04 18:47:46

标签: laravel laravel-5 phpunit

我有一个简单的功能路线:

if (Auth::check()) {
    return response()->json('true');
} else {
    return response()->json('false');
}

我需要使用PHPUnit中的类似函数测试此函数:

$this->get('auth/checkLoggedIn')
     ->seeJson([true]);

如何模拟测试用户已登录?

2 个答案:

答案 0 :(得分:3)

返回这样的回复:

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]);

}

答案 1 :(得分:0)

使用actngAs($user_id)模拟已登录的用户。

更全面的例子:

  // simulate ajax request
        $this->actingAs($user_id)               
            ->post(route('api.bookmark.store'), [
                'event' => $this->event->id,
                '_token' => csrf_token()
            ]);
相关问题