如何对Spring DateTimeFormat验证进行单元测试

时间:2018-08-17 13:31:34

标签: java spring-mvc thymeleaf

我有一个DTO类,其中包含两个日期字段。两者都用@NotNull@DateTimeFormat注释。

我正在执行TDD,我注意到成功返回了NotNull错误消息,但是当我在单元测试中传递一个日期时,即使它与我的模式不匹配,它也会接受几乎所有内容。

有趣的是,当我以百里香叶形式进行测试时,它可以正常工作,并以错误的日期形式返回我期望的错误消息。

我假设这与我仅对DTO进行单元测试时不应用DateTimeFormat的弹簧有关,那么为什么我的非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()
    );
}

}

1 个答案:

答案 0 :(得分:0)

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