在 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 的良好模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)