java DateTimeFormatterBuilder fails on testtime

こ雲淡風輕ζ 提交于 2019-11-26 06:49:57

问题


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?


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!