[英]Java Date Time conversion, unit tests fails remotely
我有一个 quarkus 应用程序,我正在将带有 GMT 偏移量的字符串时间戳转换为欧洲/柏林时间。
例如这次: "2022-08-13 10:13:56.48382+03"
我的单元测试在本地运行完全正常,但在管道中远程失败?
我以为我编写了代码来显式创建具有给定时区的时间实例,但我认为它仍然以某种方式获取管道服务器的本地时区?
我也一直在考虑改变管道时区来解决测试? https://support.circleci.com/hc/en-us/articles/115015772847-Setting-Timezone-in-2-0-MacOS-Builds
有谁知道为什么这些测试失败了?
当应用程序启动时,这将被调用TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
转换时间的逻辑
public static Date convertTime(String timestamp) {
// offset being f.e. +01, +12, -03
String gmtZone = "GMT" + getOffset(timestamp);
// removes the milliseconds from time
timestamp = stripMilliseconds(timestamp);
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(INCOMING_TIMESTAMP_FORMAT);
LocalDateTime localDateTime = LocalDateTime.parse(timestamp, dtf);
ZonedDateTime zdtGmt = ZonedDateTime.of(localDateTime, ZoneId.of(gmtZone));
ZonedDateTime zdtBerlin = zdtGmt.withZoneSameInstant(ZoneId.of(TIME_ZONE_EUROPE_BRUSSELS));
return Date.from(zdtBerlin.toInstant());
}
测试
@ParameterizedTest
@MethodSource("timestampsWithOffsetWithCorrectlyConvertedTime")
void offsetShouldBeCorrectlyConvertedToBerlinTime(String timestamp, Date expectedConvertedTime) {
Date date = TimeZoneConverter.convertTime(timestamp);
assertEquals(expectedConvertedTime, date);
}
private static Stream<Arguments> timestampsWithOffsetWithCorrectlyConvertedTime() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return Stream.of(
Arguments.of("2022-08-13 10:13:56.48382+00", sdf.parse("2022-08-13 12:13:56")),
Arguments.of("2022-09-20 22:33:16.4271382-03", sdf.parse("2022-09-21 03:33:16")),
Arguments.of("2022-11-25 16:00:00.482+12", sdf.parse("2022-11-25 05:00:00")),
Arguments.of("2022-03-03 11:33:16.483829+02", sdf.parse("2022-03-03 10:33:16"))
);
}
感谢@Dawood ibn Kareem!
我通过在测试 class 声明上方添加@QuarkusTest
设法解决了这个问题。
我相信这会使用我在 Quarkus 应用程序中设置的上下文运行测试。 这意味着TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));
now 在运行测试时被调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.