我是Laravel的新手,我需要一些帮助来重构我的代码。 现在,100%的测试中没有涵盖方法,因为我无法模拟验证器对象及其响应。 我的cotroller中有以下方法
public function store(Request $request)
{
$data = $request->only([
'name',
'email',
'message',
]);
$validator = Validator::make($data, $this->validatorRules);
if ($validator->fails()) {
return $this->response->errorFromValidator($validator);
}
$savedItem = $this->repository->store($data);
if (!$savedItem) {
return $this->response->error('Cannot save');
}
return $this->response->succesItem($savedItem);
}
我试图在控制器的构造函数中注入验证器:
function __construct(Response $response, Repository $repository, Validator $validator)
{
$this->response = $response;
$this->repository = $repository;
$this->validator= $validator;
}
并在方法中使用它:
$this->validator::make($data, $this->validatorRules);
但是我遇到了语法错误,出乎意料的是' ::' (T_PAAMAYIM_NEKUDOTAYIM)。 如何在方法之外抽象验证器,所以我可以在测试中模拟验证器?
答案 0 :(得分:2)
为什么使用Validator验证数据?
我建议您使用请求来验证表单数据,而不是在控制器中使用Validator。从您的代码我可以注意到您尝试保存联系表单,所以我的建议在这里:
运行此命令,这将在“Requests”文件夹中创建一个ContactRequest文件:
php artisan make:request ContactRequest
ContactRequest文件:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
class ContactRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required|min:5|max:20|alpha',
'email' => 'required|email',
'message' => 'required|max:250'
];
}
}
注意:您必须将自动调整设置为return true;
以避免未经授权的错误。
你的控制器:
<?php namespace App\Http\Controllers;
use App\Http\Requests\ContactRequest;
class ContactController extends Controller {
function __construct(Repository $repository)
{
$this->repository = $repository;
}
public function store(ContactRequest $request)
{
return $this->repository->store($data);
}
}
在您的视图文件中,您可以处理如下错误:
@if (count($errors) > 0)
<div class="alert alert-danger">
<button class="close" data-close="alert"></button>
@foreach ($errors->all() as $error)
<span>{{ $error }}</span>
@endforeach
</div>
@endif
或者,如果您希望逐个显示错误,可以这样做:
{!! $errors->first('name', '<small class="help-block">:message</small>') !!}
{!! $errors->first('email', '<small class="help-block">:message</small>') !!}
{!! $errors->first('message', '<small class="help-block">:message</small>') !!}
只有在ContactRequest验证数据时才会存储您的数据。
现在,您的方法应该包含在测试中,您可以注意到控制器的清洁程度。
答案 1 :(得分:0)
如果您以这种方式实例化验证器类,则不需要使用::
。
使用$this->validator->make($data, $this->validatorRules);
代替你应该能够很容易地模拟验证器类的输出。
作为旁注,为什么要模拟验证?它是纯粹的代码,并没有打到外部服务,因此您应该考虑在测试期间运行这些验证规则。