Spring MockMVC-如何模拟在控制器外部运行的自定义验证器 [英] Spring MockMVC - How to mock custom validators running outside of controllers

查看:121
本文介绍了Spring MockMVC-如何模拟在控制器外部运行的自定义验证器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

@UsernameAlreadyExists
private String username;

我创建了一个自定义验证器,以确保在提交帐户创建表单时,应用程序可以捕获重复的用户名.

I have a custom validator that I created to ensure that duplicate usernames are caught by the application when account creation form submits.

当我使用MockMVC对帐户创建控制器进行单元测试时,由于验证程序依赖于服务,因此它失败,因此我得到了空指针异常.

When I unit test the account creation controller using MockMVC, it fails as the validator depends on a service, so I get null pointer exception.

如何模拟验证器或验证器所依赖的服务? 我无法弄清楚如何使它工作,因为控制器并不显式依赖验证器,而是运行在控制器之外.

How can I mock the validator or the service this validator depends on? I could not figure out how to make this work as the controller does not depend on the validator explicitly, it runs outside of the controller.

推荐答案

您不能模拟ConstraintValidator,但可以使用模拟bean的常规spring方法模拟验证器依赖的服务,例如:

You cannot mock the ConstraintValidator but you certainly can mock the service that the validator depends on, using the usual spring ways of mocking beans, for eg.:

.1.可能使用完全相同的Bean名称定义一个模拟实例,以确保使用模拟的配置在真实实例之后加载.

.1. Potentially define a mock instance with the exact same bean name, ensuring that your config with mock gets loaded after the real instance.

.2.仅使用定义了模拟bean的测试配置进行测试.

.2. Test with only the test configuration with only the mock bean defined.

这篇关于Spring MockMVC-如何模拟在控制器外部运行的自定义验证器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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