简体   繁体   中英

How can I compare LocalDateTime in JSON after parsing it out of an Object with the same filed in the object and ignore millisecond in the comparing?

I'm testing this scenario :

I have an Object on my Test which has a LocalDateTime .

When I'm creating a JSON out of this Object via ObjectMapper, the result would be different because in the Object I have millisecond and in the JSON I don't have.

It is the line which compare the content in the response body with the string out of object:

assertThat(jsonOutOfTheObject, is(objectMapper.writeValueAsString(object)));

in Object the LocalDateTime filed would be something like:

2022-06-30T19:42:57.118286

and in the JSON-body:

2022-06-30T19:42:57

So they are not the same, and the test will be failed.

I tried truncatedTo(ChronoUnit.SECONDS) and withNano(0) but they doesn't always give me the valid result, because if the millisecond will be more than 500000, they round it up.

Any solution?

UPDATE:

I noticed that the truncate works fine, the problem is the LocalDateTime value in the JSON has been rounded up!

I added this cod for handling round up:

  private static final int MILLISECOND_EDGE_FOR_ROUND_UP = 500000000;

  private LocalDateTime roundUpSecond(LocalDateTime date) {
    if (date.getNano() > MILLISECOND_EDGE_FOR_ROUND_UP) {
        return date.plusSeconds(1).truncatedTo(ChronoUnit.SECONDS);
    }
    return date.truncatedTo(ChronoUnit.SECONDS);
}

I suppose it's an serialization issue.
You must have a custom JsonSerializer because ObjectMapper can't handle LocalDateTime out of the box as far as i know.
Thus somewhere must be a pattern for serialization, like SimpleDateFormat("dd-MM-yyyy hh:mm:ss") . Append the milliseconds to this pattern and your comparison should be fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM