在 Spring MVC 中具有基于注释的验证的单元测试表单 bean 的良好模式

Good patterns for unit testing form beans that have annotation-based validation in Spring MVC(在 Spring MVC 中具有基于注释的验证的单元测试表单 bean 的良好模式)
本文介绍了在 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?

一个明显的方法是创建一个验证器,向它抛出一个 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 的良好模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

quot;Char cannot be dereferencedquot; error(“Char 不能被取消引用错误)
Java Switch Statement - Is quot;orquot;/quot;andquot; possible?(Java Switch 语句 - 是“或/“和可能的?)
Java Replace Character At Specific Position Of String?(Java替换字符串特定位置的字符?)
What is the type of a ternary expression with int and char operands?(具有 int 和 char 操作数的三元表达式的类型是什么?)
Read a text file and store every single character occurrence(读取文本文件并存储出现的每个字符)
Why do I need to explicitly cast char primitives on byte and short?(为什么我需要在 byte 和 short 上显式转换 char 原语?)