【发布时间】:2020-10-08 10:56:54
【问题描述】:
好的,我已经尝试搜索了一段时间,以寻找有关如何以及为什么会发生这种情况的解决方案,就在这里。
在生产环境中,这段代码运行良好。
public function store(Add $request) {
$data = $request->validated();
//.... some other stuff
}
Add 是一个扩展Illuminate\Foundation\Http\FormRequest 的类,它只有一些规则(我已经检查过并且不会影响错误,是未发布的原因)
在我的测试架构中,我有几个场景,主要是验收测试,以确保根据不同的数据输入创建(或不创建)所有内容。这些调用如$this->call($uri, $body, $headers),它们按预期工作,模拟生产环境。
但是,我正在尝试编写一个特定于控制器的测试,但它一直给我这个错误:
$userController = new UserController();
$request = Add::create('/test', 'POST', $body);
$userController->store($request);
这会输出错误:
Error: Call to a member function validated() on null
vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php:188
我尝试输出 dd($request->validated()); 返回的内容,但这就是它崩溃的地方。
- 解决办法是什么?
- 为什么会这样?
【问题讨论】:
-
$this->call($uri, $body, $headers)第二个参数是$body,但您传递的是Add::create('/test', 'POST', $body);中的表单方法。也许这可能是问题所在? -
$this->call 是一个 laravel 测试用例函数,用 http 调用 URI,Add::create 是 FormRequest 的派生类,代表 HTTP 请求的主体,它们是不同的东西跨度>
标签: laravel-5 phpunit laravel-5.8 laravel-5.7