预期状态代码为200,但收到302.断言false为true失败.使用laravel 5.4中的phpunit测试



嗨,我有这个页面,它是/dno个人/cebu属性。我试着在我的laravel中使用PHPUNIT测试进行磨合。现在我在下面创建了这个测试文件

<?php
namespace TestsFeature;
use TestsTestCase;
use IlluminateFoundationTestingWithoutMiddleware;
use IlluminateFoundationTestingDatabaseMigrations;
use IlluminateFoundationTestingDatabaseTransactions;
use IlluminateHttpResponse;

class DnoPersonalTest extends TestCase
{
/**
* A basic test example.
*
* @test
*/
public function add_cebu_properties_page()
{

$response = $this->get('/dno-personal/cebu-properties');
$response->assertStatus(200);
}
}

现在,在我的路由文件中,我还没有为dno个人/cebu属性创建路由,我在phpunit中运行了测试,它抛出了错误

Expected status code 200 but received 404.
Failed asserting that false is true.
C:xampphtdocsdnogroupvendorlaravelframeworksrcIlluminateFoundationTestingTestResponse.php:79
C:xampphtdocsdnogrouptestsFeatureDnoPersonalTest.php:24
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

我认为这是可以的,因为我还没有路由,这会抛出404的错误。现在,当我添加到路线

Route::get('/dno-personal/cebu-properties',
'DnoPersonalController@cebuProperties')
->name('dno-personal.cebuProperties');

在我的控制器cebuProperties中没有方法的情况下,当我运行测试PHPUNIT时,它会抛出

Expected status code 200 but received 302.
Failed asserting that false is true.
C:xampphtdocsdnogroupvendorlaravelframeworksrcIlluminateFoundationTestingTestResponse.php:79
C:xampphtdocsdnogrouptestsFeatureDnoPersonalTest.php:24
FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

它抛出302的错误。现在我希望它抛出尚未创建的方法,而不是302。现在,当我添加$this->withoutExceptionHandling();时,会抛出一个错误

PHP Fatal error:  Call to undefined method TestsFeatureDnoPersonalTest::withoutExceptionHandling() in C:xampphtdocsdnogrouptestsFeatureDnoPersonalTest.php on line 22
In DnoPersonalTest.php line 22:
Call to undefined method TestsFeatureDnoPersonalTest::withoutExceptionHandling()

Fatal error: Call to undefined method TestsFeatureDnoPersonalTest::withoutExceptionHandling() in C:xampphtdocsdnogrouptestsFeatureDnoPersonalTest.php on line 22

它看不到$this->withoutExceptionHandling();,有人能帮我弄清楚吗?我们非常感谢任何帮助。TIA-

问题是您的路由应用了auth中间件,这意味着请求甚至在到达您的路由之前就被重定向到登录页面。

您必须创建并验证用户才能正确测试此路由,Laravel为此提供了actingAs助手。

来自文档:

当然,会话的一个常见用途是维护已验证的用户。actingAs helper方法提供了一个简单的将给定用户验证为当前用户的方式。例如,我们可以使用模型工厂生成并验证用户:

<?php
use AppUser;
class ExampleTest extends TestCase
{
public function testApplication()
{
$user = factory(User::class)->create();
$response = $this->actingAs($user)
->withSession(['foo' => 'bar'])
->get('/');
}
}

当我测试一个应该返回422状态的用例时,就会发生这种情况,这是一个验证用例。我通过在测试中定义标题来解决这个问题。所以一定要像这样使用Accept: application/json

$this
->withHeaders(['Accept' => 'application/json'])
->post("api/{$this->apiVersion}/auth/register", $requestBody)
->assertStatus(422);

参考:https://laravel.com/docs/9.x/sanctum#spa-身份验证

在我的案例中,我使用了一个重定向的个性化请求,因为验证失败。在查看数据之前,我设置了默认请求并运行良好,我的个性化请求也运行良好。

最新更新