I have a DTO class holding two date fields. Both are annotated with a @NotNull
and @DateTimeFormat
.
I'm doing TDD and I noticed my NotNull
error message is returned successfully but when I pass in a date in my unit test it accepts pretty much anything even if it doesn't match my pattern.
Interestingly when I test in my thymeleaf form it works correctly, giving me back the error message I expect with a malformed date.
I'm assuming this is something to do with spring not applying the DateTimeFormat when I unit test just the DTO but then why would my not null work as expected?
I've provided the code for the DTO below
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
}
Unit Test:
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()
);
}
}
Simple answer, you cannot test a Spring constraint outside of the spring container. I was attempting to test in the way I would test my javax validations