【问题标题】:Failing authentication test, using Laravel, phpunit and Homestead身份验证测试失败,使用 Laravel、phpunit 和 Homestead
【发布时间】:2019-09-10 16:53:21
【问题描述】:

所以,我正在尝试在 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 和测试非常陌生,我才刚刚开始了解它是如何工作的。

【问题讨论】:

    标签: authentication laravel-5 phpunit homestead


    【解决方案1】:

    问题与缓存有关。

    首先必须读取文件phpunit.xml,因为您需要:<server name="APP_ENV" value="testing"/>

    在你的测试之前使用命令

     php artisan config:clear
    

    之后您的dump(config('app.env')); 将是testing(而不是local)。

    然后一切正常。

    【讨论】:

      【解决方案2】:

      我也遇到过同样的问题。对于单元测试,应该禁用 CSRF 令牌验证,但前提是您在 APP_ENV=testing 下运行。我虽然 phpunit.xml 覆盖了我的“本地”配置,所以它被设置为“测试”。不是,因为 PhpStorm 没有读取这个文件。

      如果您使用的是 PHPStorm,请不要忘记检查默认配置文件的路径 - phpunit.xml。 (设置 -> 语言和框架 -> PHP -> 测试框架)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-24
        • 2022-01-04
        • 2014-05-29
        • 2014-07-05
        • 2014-08-16
        • 1970-01-01
        相关资源
        最近更新 更多