【发布时间】:2019-01-24 13:33:07
【问题描述】:
我有一个包含两个日期字段的 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;
@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()
);
}
}
【问题讨论】:
-
能否提供单元测试的代码。
-
我不确定
@DateTimeFormat注释的用途,但它看起来不像用于验证 - 请注意它不在javax.validation包中:docs.spring.io/spring/docs/current/javadoc-api/org/… -
@DaveyDaveDave 我想这是我问题的答案,我想我已经知道了。 DateTimeFormat 注释是一个在 mvc 端工作的 spring 框架约束,因为这个 DTO 测试没有在 spring 容器中运行,所以我无法测试它。我想我的问题真的是那么从我的 mvc 测试中测试这个的唯一方法是什么?
标签: java spring-mvc thymeleaf