在对表单 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?
一个明显的方法是创建一个验证器,向它抛出一个 null 并期望它失败.但在我看来,这不是最好的方法,因为您将使用它而不是信任框架来测试 @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?
您还可以为您的 Bean 编写单元测试,这些单元测试使用 JSR303 使用验证器工厂进行注释.参见示例:http://musingsofaprogrammingaddict.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 的良好模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!