Java Date Time conversion, unit tests fails remotely

Viewed 79

I've got a quarkus application where I'm converting a String timestamp with a GMT offset to Europe/Berlin time.

For example this time: "2022-08-13 10:13:56.48382+03"

I've got unit tests that runs completely fine locally but fails remotely in the pipeline?

I thought I wrote code to explicitly create a time instance with the given timezone, but I'm thinking it still picks up the local timezone of the pipeline server somehow?

I've also been looking into maybe changing the pipeline timezone to solve the test? https://support.circleci.com/hc/en-us/articles/115015772847-Setting-Timezone-in-2-0-MacOS-Builds

Does anyone have answers why these tests fails?

When application starts this will get invoked TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin"));

Logic to convert time

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());
}

TESTS

@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"))

    );
}
1 Answers

Thanks to @Dawood ibn Kareem!

I managed to solve this issue by adding @QuarkusTest above the test class declaration.

I believe this runs the tests with the context that I've set up in the Quarkus Application. Meaning that TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin")); now is invoked when running the tests.

Related