java DateTimeFormatterBuilder 在测试时失败 [英] java DateTimeFormatterBuilder fails on testtime

查看:26
本文介绍了java DateTimeFormatterBuilder 在测试时失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个针对 DateTimeFormatterBuilder 的简单 jUnit 测试.在运行时它可以工作,当一些 String 出现在 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.

有人有想法吗?

推荐答案

月份名称为英文,所以最好在格式化程序中设置一个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 在测试时失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆