我有一个 DTO 类,其中包含两个日期字段。两者都用@NotNull和注释@DateTimeFormat。我正在执行 TDD,我注意到我的NotNull错误消息已成功返回,但是当我在单元测试中传入一个日期时,它几乎接受任何内容,即使它与我的模式不匹配。有趣的是,当我以 thymeleaf 形式进行测试时,它可以正常工作,并返回我期望的错误消息,日期格式错误。我假设这与 spring 在我只对 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;@Beforepublic void setUp() throws Exception { tested = new HoursTracker(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); validator = factory.getValidator();}@Testpublic 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());}@Testpublic 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() );}
添加回答
举报
0/150
提交
取消