Laravel 测试用例测试重定向到某个路由

Shi*_*hiv 4 php phpunit unit-testing laravel laravel-5

我正在使用 PHPUnit 为我的 Laravel 应用程序编写一些测试用例。

下面是产生错误的类:

<?php

namespace Test\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Foundation\Testing\DatabaseMigrations;

class UserLoginTest extends TestCase
{
    use DatabaseMigrations;

    public function setUp()
    {
        parent::setUp();
        $this->admin = factory(User::class)->create([
                'is_admin'  => true,
                'password'  => bcrypt('secret'),
            ]);
    }

    /** @test */
    public function test_login_user_form()
    {
        $this->get('/login')
            ->assertStatus(200);
    }

    /** @test */
    public function test_login_user_form_submission()
    {
        $this->post('/login', [
                'email'     => $this->admin->email,
                'password'  => 'secret',
            ]);

        $this->assertRedirectedTo('/');
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是当我运行 PHPUnit 时出现以下错误:

PHPUnit 5.7.20 由 Sebastian Bergmann 和贡献者编写。....E .. 7 / 7 (100%) 时间:1.65 秒,内存:20.00MB 有 1 个错误:1) Test\Feature\UserLoginTest::test_login_user_form_submission 错误:调用未定义的方法 Test\Feature\UserLoginTest: :assertRedirectedTo()/Users/shivampaw/Desktop/valet/UltimateCRM/tests/Feature/UserLoginTest.php:37

它说这assertRedirectedTo是一个未定义的方法,但我不知道为什么。我已经尝试过类似的方法assertRedirect,但无法使其正常工作!

Dov*_*ski 7

你需要打电话assertRedirect而不是assertRedirectedToresponse此外,所有断言都需要在对象上调用

/** @test */
public function test_login_user_form_submission()
{
    $this->post('/login', [
        'email'     => $this->admin->email,
        'password'  => 'secret',
    ])->assertRedirect('/'); // <-- Chain it to the response
}
Run Code Online (Sandbox Code Playgroud)

  • @Shiv没有这样的方法,但你可以使用 `route()` 辅助函数,例如: `assertRedirect(route('some_route'))` (3认同)