laravel - 测试检查用户是否已登录 laravel

标签 laravel laravel-5 phpunit

我有一个简单的功能途径:

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/

相关文章:

laravel - 如果用户名或电子邮件为空,则停止 Laravel 密码验证

php - 让一个变量可以在 Laravel 应用程序的任何地方访问

php - 如何根据laravel上博客文章的user_id显示用户的照片?

mysql - 将 Laravel 应用程序连接到另一个数据库 - Laravel 5.8

php - 使用 PostgreSQL 在 laravel 5.5 中迁移错误

configuration - phpunit 默认测试目录(用于 travis 集成)

php - 为什么在 wamp 上更新 php 7.1.3 后 laravel 5.6 没有安装?

php - 我该如何解决 "laravel/horizon v1.1.0 requires ext-pcntl * -> the requested PHP extension pcntl is missing from your system"?

php - 更新 mockery 的 andReturn

unit-testing - Symfony2登录FOS UserBundle进行功能测试