I have a simple jUnit test for DateTimeFormatterBuilder
.
At runtime it works, when some String
comes on Spring-MVC hanlder (@RequestParam
)
At testtime it fails with the same String
value.
Tested value: 25-May-2018 11:10
Method to be tested:
public void getTimeDifference(@RequestParam String startDate, @RequestParam String endDate) {
DateTimeFormatter DATE_TIME_FORMAT = new DateTimeFormatterBuilder().parseCaseInsensitive().appendPattern("dd-MMM-yyyy HH:mm").toFormatter();
LocalDateTime.parse(startDate,DATE_TIME_FORMAT);
return messages;
}
Test-Method:
@Test
public void testFormat() throws Exception {
final String startDateFormatA = "25-May-2018 11:10";
final String endDateFormatA = "25-May-2018 11:10";
assertEquals("06:00", callDbController.getTimeDifference(startDateFormatA, endDateFormatA)[1]);
}
My Test: At runtime I set a break-point and test it on Display-View:
LocalDateTime.parse("25-May-2018 11:10",DATE_TIME_FORMAT)
At testtime with the same spring-aplication-context I do the same like on runtime and it fails.
Does anyboby have ideas?
The month name is in English, so you'd better set a java.util.Locale
in the formatter.
If you don't set it, the formatter will use the JVM default locale. And if it's not English, you might get an error (and different environments might have different configurations, so it's better to set the locale instead of relying on the JVM's default).
Just do toFormatter(Locale.ENGLISH)
instead of just toFormatter()
and that's it.
来源:https://stackoverflow.com/questions/50526234/java-datetimeformatterbuilder-fails-on-testtime