使用注释时模拟Spring MVC BindingResult [英] Mocking Spring MVC BindingResult when using annotations
问题描述
我正在迁移Spring MVC控制器以使用较新的样式注释,并希望对验证命令对象的控制器方法进行单元测试(请参见下面的简单示例).
I'm migrating a Spring MVC controller to use the newer style annotations, and want to unit test a controller method that validates a command object (see simple example below).
@RequestMapping(method = RequestMethod.POST)
public String doThing(Command command, BindingResult result,
HttpServletRequest request, HttpServletResponse response,
Map<String, Object> model){
ThingValidator validator = new ThingValidator();
validator.validate(command, result);
... other logic here
}
我的问题是我必须在单元测试中调用控制器的方法,并提供模拟值以满足其签名以正确执行代码,而我无法解决如何模拟BindingResult的问题.
My problem is I have to call the controller's method in my unit test, and provide mock values to satisfy its signature to exercise the code properly, and I cannot work out how to mock a BindingResult.
在旧样式的Controller中,签名仅采用了HttpServletRequest和HttpServletResponse,它们很容易被模拟,但是由于新注释风格的灵活性,人们不得不通过签名传递更多信息.
In the old style Controller the signature simply took a HttpServletRequest and HttpServletResponse, which were easily mockable, but due to the flexibility of the new annotation style, one has to pass a lot more in via the signature.
如何模拟Spring BindingResult用于单元测试?
How can one mock a Spring BindingResult for use in a unit test??
推荐答案
BindingResult是一个接口,所以您不能简单地传入该接口的Springs实现之一吗?
BindingResult is an interface so can you not simply pass in one of Springs implementations of that interface?
我在Spring MVC代码中不使用注释,但是当我想测试验证器的validate方法时,我只是传入BindException的实例,然后使用在assertEquals等中返回的值.
I don't use annotations in my Spring MVC code but when I want to test the validate method of a validator I just pass in an instance of BindException and then use the values it returns in assertEquals etc.
这篇关于使用注释时模拟Spring MVC BindingResult的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!