【问题标题】:Laravel test case tests redirect to a certain routeLaravel 测试用例测试重定向到某个路由
【发布时间】:2017-10-30 06:33:01
【问题描述】:

我正在使用 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('/');
    }
}

问题是当我运行 PHPUnit 时出现这个错误:

Sebastian Bergmann 和贡献者的 PHPUnit 5.7.20。 ....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 之类的方法,但无法正常工作!

【问题讨论】:

    标签: php laravel unit-testing laravel-5 phpunit


    【解决方案1】:

    您需要致电 assertRedirect 而不是 assertRedirectedTo。此外,所有断言都需要在 response 对象上调用

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

    【讨论】:

    • 如果我想 assertRedirectRoute 怎么办?
    • @Shiv 没有这样的方法,但你可以使用 route() 辅助函数,例如:assertRedirect(route('some_route'))
    猜你喜欢
    • 1970-01-01
    • 2018-04-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 1970-01-01
    • 2014-10-22
    • 2019-09-20
    相关资源
    最近更新 更多