【问题标题】:Laravel 5.7: Phpunit error - call to a member function getBag() on a stringLaravel 5.7:Phpunit 错误 - 调用字符串上的成员函数 getBag()
【发布时间】:2018-09-14 13:41:37
【问题描述】:

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

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

似乎是什么问题?

谢谢。

【问题讨论】:

    标签: php laravel phpunit laravel-5.7


    【解决方案1】:

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

    文档 - Calling Routes From Tests

    试试这个

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

    【讨论】:

    • 不,错误仍然存​​在,和以前一样
    【解决方案2】:

    改为这样做:

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

    【讨论】:

    • 我相信你不能那样做,重定向来自响应,所以当更改为 $this 时,它会说未定义的方法 assertRedirect()
    • 让我们调试...做一个dd($response)...你看到了什么?
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 2019-06-20
    • 2017-12-17
    • 2022-11-10
    • 2019-11-23
    • 2020-03-01
    • 2021-12-10
    相关资源
    最近更新 更多