0

我正在测试将数据保存到数据库中。当缺少必填字段时,我抛出异常,然后从我的控制器重定向:

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()

似乎是什么问题?

谢谢。

4

2 回答 2

0

改为这样做:

$response = $this->call('POST',  "/courses/", $data);

$response->assertRedirect('/courses/create');
$response->assertSessionHasErrors();
$response->assertHasOldInput();
于 2018-09-14T05:13:17.303 回答
0

我认为你应该使用call方法而不是post

Docs -从测试中调用路由

尝试这个

$response = $this->call("POST", "/courses/", $data);
$response = $this->assertRedirect('/courses/create');
$response = $this->assertSessionHasErrors();
$response = $this->assertHasOldInput();
于 2018-09-14T05:15:55.457 回答