如何在 Laravel 5 中测试表单请求规则?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29794549/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:25:10  来源:igfitidea点击:

How to test form request rules in Laravel 5?

formsunit-testinglaraveltestingrequest

提问by kant312

I created a form request class and defined a bunch of rules. Now I would like to test these rules to see if the behaviour meets our expectations.

我创建了一个表单请求类并定义了一堆规则。现在我想测试这些规则,看看行为是否符合我们的期望。

How could I write a test to accomplish that?

我怎么能写一个测试来实现这一点?

Many thanks in advance for your answers!

非常感谢您的回答!

Update: more precisely, I would like to write a unit test that would check e.g. if a badly formatted email passes validation or not. The problem is that I don't know how to create a new instance of the Request with fake input in it.

更新:更准确地说,我想编写一个单元测试来检查例如格式错误的电子邮件是否通过验证。问题是我不知道如何使用假输入创建请求的新实例。

采纳答案by Margus Pala

You need to have your form request class in the controller function, for example

例如,您需要在控制器功能中有表单请求类

public function store(MyRequest $request)

Now create HTML form and try to fill it with different values. If validation fails then you will get messages in session, if it succeeds then you get into the controller function.

现在创建 HTML 表单并尝试用不同的值填充它。如果验证失败,您将在会话中收到消息,如果验证成功,您将进入控制器功能。

When Unit testing then call the url and add the values for testing as array. Laravel doc says it can be done as

当单元测试然后调用 url 并将测试值添加为数组。Laravel 文档说它可以做到

$response = $this->call($method, $uri, $parameters, $cookies, $files, $server, $content);

回答by Martins Balodis

The accepted answer tests both authorization and validation simultaneously. If you want to test these function separately then you can do this:

接受的答案同时测试授权和验证。如果你想分别测试这些功能,那么你可以这样做:

test rules():

测试rules()

$attributes = ['aa' => 'asd'];
$request = new MyRequest();
$rules = $request->rules();
$validator = Validator::make($attributes, $rules);
$fails = $validator->fails();
$this->assertEquals(false, $fails);

test authorize():

测试authorize()

$user = factory(User::class)->create();
$this->actingAs($user);
$request = new MyRequest();
$request->setContainer($this->app);
$attributes = ['aa' => 'asd'];
$request->initialize([], $attributes);
$this->app->instance('request', $request);
$authorized = $request->authorize();
$this->assertEquals(true, $authorized);

You should create some helper methods in base class to keep the tests DRY.

您应该在基类中创建一些辅助方法以保持测试干燥。