Laravel 5.7:Phpunit错误-在字符串上调用成员函数getBag()

时间:2018-09-14 04:51:41

标签: php laravel phpunit phpunit-testing laravel-5.7

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

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

似乎是什么问题?

谢谢。

2 个答案:

答案 0 :(得分:0)

执行此操作:

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

$response->assertRedirect('/courses/create');
$response->assertSessionHasErrors();
$response->assertHasOldInput();

答案 1 :(得分:0)

我认为您应该使用 call 方法而不是发布

文档-Calling Routes From Tests

尝试一下

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