如何模拟唯一验证规则? [英] How can I mock unique validation rule?

查看:107
本文介绍了如何模拟唯一验证规则?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为ResourceControllerstore()函数编写测试用例,该功能在数据库中添加了新资源.

I am writing test cases for a store() function of a ResourceController which adds a new resource in database.

在我的测试案例中,我不允许访问数据库,因此我在嘲笑所有数据库交互&现在,我需要模拟unique验证规则.

I am not allowed to access database in my test cases, So I am mocking all the database interactions & now I need to mock the unique validation rule.

我已经Google搜索了&甚至在stackoverflow上搜索,但我没有 找到任何具体的东西.

I have Googled it & even searched on the stackoverflow but I didn't found anything specific.

这是我所知道的:- 我可以模拟\Validator::getPresenceVerifier() & \Validator::setPresenceVerifier(),但是如果我模拟它们,那么我将无法制作验证器对象. 此处的StackOverflow问题

Here is what I know:- I can mock the \Validator::getPresenceVerifier() & \Validator::setPresenceVerifier() but if I mock them, then i will not be able to make the validator object. StackOverflow Question Here

谁能引导我正确的方向.

Can anyone guide me in the right direction.

推荐答案

好,给您一些想法:首先,Validator是一个Facade,这意味着您可以使用Validator :: shouldReceive模拟它的任何方法.您也可以使用Validator::swap($mock)模拟整个根对象.如果您的控制器使用的是$this->validate,则还可以通过替换内部验证器实例来模拟验证器-我怀疑您甚至可以在创建控制器时使用IoC容器注入它.

Ok, here are some ideas for you: First, the Validator is a facade, which means you can mock any method of it with Validator::shouldReceive. You can also mock the whole root object with Validator::swap($mock). If your controller is using $this->validate, you can also mock the validator by replacing the internal validator instance - I suspect you might even be able to use the IoC container to inject it when you create the controller.

如果所有其他方法都失败了,您还可以通过创建控制器的模型,然后在控制器模型上调用该方法来测试该方法-这样,您就可以模拟其他内部方法(例如,验证).您可以直接测试该方法,也可以再次使用App::bind映射您的模拟,以便其从调用方法中触发.

If all else fails, you can also test the method by creating a mock of the controller, and then calling the method on your controller mock - that way you can mock other internal methods (e.g. the validation). You can test the method directly, or use App::bind again to map your mock so that it triggers from the call method.

如果您正在使用自定义Request类进行验证,则还可以尝试模拟该类以完全禁用验证,或者使用自定义验证功能(而不是唯一的测试)将其替换为您自己的验证器.

If you are validating with a custom Request class, you can also try mocking that one to disable the validation entirely, or replace it with your own validator using a custom validation function instead of the unique test.

这篇关于如何模拟唯一验证规则?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆