【问题标题】:Why is my unit test failing when all I'm trying to do is test the endpoint of the home view?当我要做的只是测试主视图的端点时,为什么我的单元测试失败了?
【发布时间】:2021-11-19 22:35:52
【问题描述】:

我在Laravel Framework 5.6.38 - 我正在做一个简单的测试,我只想测试主页,它应该返回一个200 但相反,它返回了下面的错误。主页是在 web.php 文件中定义的,所以没有问题。

我只是不确定如何解决这个问题。

Time: 274 ms, Memory: 20.00MB

There was 1 failure:

1) Tests\Feature\UserTest::testExample
Expected status code 200 but received 302.
Failed asserting that false is true.

/home/vagrant/project/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:124
/home/vagrant/project/tests/Feature/UserTest.php:19

这里是UserTest.php

<?php

namespace Tests\Feature;

use Tests\TestCase;

class UserTest extends TestCase
{
    public function testExample()
    {
        $response = $this->get('/home');
        $response->assertStatus(200);
    }
}

这是.env.testing 文件:

APP_NAME="Project"
APP_ENV=local
APP_KEY=base64:somekey
APP_DEBUG=true
APP_URL=http://local.test

这里是phpunit.xml

<?xml version="1.0" encoding="UTF-8"?>

<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Unit">
            <directory suffix="Test.php">./tests/Unit</directory>
        </testsuite>

        <testsuite name="Feature">
            <directory suffix="Test.php">./tests/Feature</directory>
        </testsuite>
    </testsuites>
    <filter>
        <whitelist processUncoveredFilesFromWhitelist="true">
            <directory suffix=".php">./app</directory>
        </whitelist>
    </filter>
    <php>
        <env name="APP_ENV" value="local"/>
        <env name="BCRYPT_ROUNDS" value="4"/>
        <env name="CACHE_DRIVER" value="array"/>
        <env name="SESSION_DRIVER" value="array"/>
        <env name="QUEUE_DRIVER" value="sync"/>
        <env name="MAIL_DRIVER" value="array"/>
    </php>
</phpunit>

【问题讨论】:

  • 你得到一个 302,这是一个重定向。它可以在您的浏览器中使用吗?
  • @ChinLeung 是的,它适用于我的浏览器
  • @TimLewis 哦,是的,我喜欢 facepalm。我需要在方法中调用一些面向身份验证的东西才能完成这项工作,对吧?
  • 是的,302 重定向将您踢回登录屏幕进行身份验证 ????我真的不知道这样做的方法,还没有使用这个套件进行 Laravel 测试,但这可能是你问题的核心。
  • @TimLewis 明白了,非常感谢!

标签: php laravel debugging phpunit


【解决方案1】:

如果您因为未登录测试而被重定向 (302),您可以尝试模拟用户并将用户设置为已登录,然后再运行测试。

在“api”驱动程序中创建和登录的用户片段:

$user = factory(User::class)->create();
$this->be($user, 'api');

您也可以尝试跳过检查登录的中间件:

$this->withoutMiddleware(AuthMiddlware::class);

如果可行,我会创建一个 Trait 并将其添加到您需要的测试用例中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 2016-10-05
    • 1970-01-01
    相关资源
    最近更新 更多