【问题标题】:Laravel Testing assertRedirect for unauthenticated user未经身份验证的用户的 Laravel 测试 assertRedirect
【发布时间】:2021-11-23 17:22:55
【问题描述】:

经过多次尝试,我写到这里,但我的问题还没有解决。

我想在 Laravel 上使用 PHPUnit 创建一个测试,我的类具有如下所述的功能:

public function test_not_connected_user_can_not_create_new_task() {
            
    $this->withoutExceptionHandling();

    //Given we have a task object
    $task = Task::factory()->make();

    // When unauthenticated user submits post request to create task endpoint
    // He should be redirected to login page
    $this->post('/tasks/store',$task->toArray())
        ->assertRedirect(route('login'));
}

这是我的路线:

Route::post('/tasks/store', [App\Http\Controllers\TaskController::class, 'store'])
    ->name('store');

还有我的控制器功能:

public function __construct() {
    $this->middleware('auth')->except(['index','show']);
}

/**
 * Store a newly created resource in storage.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function store(Request $request) {
    $task = Task::create([
        'title' => $request->get('title'),
        'description' => $request->get('description'),
        'user_id' => Auth::id()
    ]);

    return redirect()->route('show', [$task->id]);
}

我们在这里有一个middleware 来管理身份验证。

当我运行测试时:

vendor/bin/phpunit --filter test_connected_user_can_create_new_task

我收到此错误:

  1. Tests\Feature\TasksTest::test_not_connected_user_can_not_create_new_task Illuminate\Auth\AuthenticationException:未经身份验证。

它指向这一行:

$this->post('/tasks/store', $task->toArray())

预期的行为是它应该重定向到登录,但这里测试失败,我不明白为什么。

谢谢

【问题讨论】:

    标签: php laravel unit-testing phpunit


    【解决方案1】:

    这个问题非常容易解决。你有$this->withoutExceptionHandling();,这实际上是在抛出错误,你想要的是捕捉它并让一切继续。为此,请删除该行代码,您的测试将正常运行。

    【讨论】:

    • 没关系,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2020-11-15
    • 2016-01-17
    相关资源
    最近更新 更多