在 Spring MVC 中具有基于注解的验证的单元测试表单 bean 的良好模式 [英] Good patterns for unit testing form beans that have annotation-based validation in Spring MVC

查看:32
本文介绍了在 Spring MVC 中具有基于注解的验证的单元测试表单 bean 的良好模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对表单 bean 使用基于注解的验证时,对这些 bean 进行单元测试以确保为每个字段指定正确的验证注解的最佳实践是什么?

When using annotation based validation for a form bean, what is the best practice for unit-testing those beans in order to ensure that correct validations annotations are specified for each field?

例如,如果您有:

public class MyForm {
    @NotNull
    private String name;
}

验证应用了 @NotNull 的最佳方法是什么?

What is the best way to verify that @NotNull is applied to it?

一个明显的方法是创建一个验证器,向它抛出一个空值并期望它失败.但在我看来,这不是最好的方法,因为您将使用它而不是信任框架来测试 @NotNull 的行为和实现.

One obvious way is to create a validator, throw a null at it and expect it to fail. But in my view this is not the best way as you'll be testing the behaviour and implementation of @NotNull using that rather than trusting the framework.

理想情况下,我想使用反射或实用程序,让我可以断言 @NotNull(和任何其他)验证应用于给定字段,而不必发送验证失败的各种值组合.

Ideally I would want to use reflection or a utility that gives me the possibility of just asserting that an @NotNull (and any other) validation is applied to a given field, rather than having to send various combination of values that fail validation.

是否有一种优雅的方法可以做到这一点,或者我总体上是否在正确的轨道上?

Is there an elegant way of doing this, or am I on the right track in general?

推荐答案

您还可以使用验证器工厂为使用 JSR303 注释的 Bean 编写单元测试.见示例:http://musingsofaprogrammingaccident.blogspot.com/2009/02/using-bean-validation-with-spring.html

You can also write unit tests for your Beans which are annotated usin JSR303 using validator factory. See example: http://musingsofaprogrammingaddict.blogspot.com/2009/02/using-bean-validation-with-spring.html

这篇关于在 Spring MVC 中具有基于注解的验证的单元测试表单 bean 的良好模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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