Problem:
A unit test for DateTimeFormatterBuilder fails with the same input string that works in runtime. The string value under test is "25-May-2018 11:10".
Method Being 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]); }
Investigation:
Solution:
The problem arises due to the use of the JVM's default locale for parsing the month name in the string. To resolve it, specify the Locale.ENGLISH locale while creating the formatter.
DateTimeFormatter DATE_TIME_FORMAT = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendPattern("dd-MMM-yyyy HH:mm") .toFormatter(Locale.ENGLISH);
By setting the locale explicitly, the formatter ensures consistent parsing regardless of the JVM's default locale, resolving the issue in the test environment.
The above is the detailed content of Why Does My DateTimeFormatterBuilder Unit Test Fail, But Runtime Works with the Same Input String?. For more information, please follow other related articles on the PHP Chinese website!