首页 > 解决方案 > 如何对春季日期时间格式验证进行单元测试

问题描述

我有一个包含两个日期字段的 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()
    );
}

}

标签: javaspring-mvcthymeleaf

解决方案


简单的答案,您不能在 spring 容器之外测试 Spring 约束。我试图以测试我的 javax 验证的方式进行测试


推荐阅读