【发布时间】: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
我收到此错误:
- 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