問題描述
我對 DateTimeFormatterBuilder
有一個簡單的 jUnit 測試.在運行時,當 Spring-MVC 處理程序 (@RequestParam
)
I have a simple jUnit test for DateTimeFormatterBuilder
.
At runtime it works, when some String
comes on Spring-MVC hanlder (@RequestParam
)
在測試時它以相同的 String
值失敗.
At testtime it fails with the same String
value.
測試值:25-May-2018 11:10
待測方法:
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
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]);
}
我的測試:在運行時我設置一個斷點并在 Display-View 上測試它:
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)
在測試時使用相同的 spring-aplication-context 我在運行時做同樣的事情,但它失敗了.
At testtime with the same spring-aplication-context I do the same like on runtime and it fails.
有人有想法嗎?
推薦答案
月份名稱是英文的,所以你最好在formatter中設置一個java.util.Locale
.
The month name is in English, so you'd better set a java.util.Locale
in the formatter.
如果不設置,格式化程序將使用 JVM 默認語言環境.而且如果不是英文,可能會報錯(而且不同的環境可能有不同的配置,所以最好設置locale而不是依賴JVM的默認值).
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).
只需執行 toFormatter(Locale.ENGLISH)
而不是 toFormatter()
即可.
Just do toFormatter(Locale.ENGLISH)
instead of just toFormatter()
and that's it.
這篇關于java DateTimeFormatterBuilder 在測試時間失敗的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!