java - 如何对春季日期时间格式验证进行单元测试
问题描述
我有一个包含两个日期字段的 DTO 类。两者都用 a@NotNull
和注释@DateTimeFormat
。
我正在做 TDD,我注意到我的NotNull
错误消息已成功返回,但是当我在单元测试中传递一个日期时,即使它与我的模式不匹配,它也会接受几乎任何东西。
有趣的是,当我以 thymeleaf 形式进行测试时,它可以正常工作,并返回我期望的错误消息,并且日期格式不正确。
我假设这与春天在我仅对 DTO 进行单元测试时不应用 DateTimeFormat 有关,但是为什么我的 not null 会按预期工作?
我在下面提供了 DTO 的代码
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotNull;
import java.util.Date;
public class HourTracker {
@NotNull(message = "start time cannot be null")
@DateTimeFormat(pattern = "hh:mma")
private Date startTime;
@NotNull(message = "end time cannot be null")
@DateTimeFormat(pattern = "hh:mma")
private Date endTime;
//getters and setters
}
单元测试:
public class HourTrackerTest {
private static final String HOURS_INPUT_FORMAT = "hh:mma";
private Validator validator;
private HoursTracker tested;
@Before
public void setUp() throws Exception {
tested = new HoursTracker();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
@Test
public void testValidTimeInputs() throws Exception {
SimpleDateFormat timeFormatForDate = new SimpleDateFormat(HOURS_INPUT_FORMAT);
Date validTimeInput = timeFormatForDate.parse("12:30pm");
tested.setStartTime(validTimeInput);
tested.setEndTime(validTimeInput);
assertEquals("Start time was not correctly set", validTimeInput, tested.getStartTime());
assertEquals("End time was not correctly set", validTimeInput, tested.getStartTime());
}
@Test
public void testNullStartTimeInputErrorMessage() throws Exception {
tested.setStartTime(null);
Set<ConstraintViolation<HoursTrackingForm>> violations = validator.validate(tested);
assertFalse("No violation occurred, expected one", violations.isEmpty());
assertEquals("Incorrect error message",
"Please enter a valid time in AM or PM",
violations.iterator().next().getMessage()
);
}
@Test
public void testNullEndTimeInputErrorMessage() throws Exception {
tested.setEndTime(null);
Set<ConstraintViolation<HoursTrackingForm>> violations = validator.validate(tested);
assertFalse("No violation occurred, expected one", violations.isEmpty());
assertEquals("Incorrect error message",
"Please enter a valid time in AM or PM",
violations.iterator().next().getMessage()
);
}
}
解决方案
简单的答案,您不能在 spring 容器之外测试 Spring 约束。我试图以测试我的 javax 验证的方式进行测试
推荐阅读
- python - 将当前模型从models.Model集成到BaseModel django
- javascript - 制表符 4 - 图像未显示
- angular - 过滤后将可观察响应传递给下一个可观察对象
- mysql - 突然无法访问phpmyadmin上的数据库
- html - 从表格中删除填充
- java - URL.getRef() 和 URI.getFragment() 是否相同?
- java - 失败的测试在 testng 输出中显示为通过
- php - wordpress 查询 orderby 作者角色
- swift - 快速,在后台检测 ibeacons 并在范围内发送通知
- c - 程序为静态对象、自动对象和动态分配的对象使用不同的内存区域