我正在测试将数据保存到数据库中。当缺少必填字段时,我抛出异常,然后从我的控制器重定向:
try {
$product = Product::create([
'name' => $request->name,
'description' => $request->description,
]);
return redirect('home')->with('success', 'Record has been added');
} catch(\Exception $e) {
return redirect()->to('course/create')
->withInput($request->input())
->with('errors', 'Required Fields Not Submitted');
}
我想测试重定向,会话是否有错误以及是否返回传递的初始数据以填充表单,所以在我的单元测试中我有:
$response = $this->post("/courses/", $data);
$response->assertRedirect('/courses/create');
$response->assertSessionHasErrors();
//$response->assertSessionHasAll();
$response->assertHasOldInput();
但是当我遇到assertSessionHasErrors时,我得到了:
错误:在字符串上调用成员函数getBag()
当我遇到assertHasOldInput时,我得到:
BadMethodCallException:调用未定义的方法Illuminate \ Http \ RedirectResponse :: assertHasOldInput()
似乎是什么问题?
谢谢。
我认为你应该使用call方法而不是post
文件 - Calling Routes From Tests
试试这个
$response = $this->call("POST", "/courses/", $data);
$response = $this->assertRedirect('/courses/create');
$response = $this->assertSessionHasErrors();
$response = $this->assertHasOldInput();
改为:
$response = $this->call('POST', "/courses/", $data);
$response->assertRedirect('/courses/create');
$response->assertSessionHasErrors();
$response->assertHasOldInput();