4

I have a resource that returns me an object with java.time.Instant property.

class X {
    ...
    private Instant startDate;
    ...
}

And I am testing it with:

    mockMvc.perform(get("/api/x"))
        .andExpect(status().isOk())
        .andExpect(jsonPath("$.content.[*].startDate").value(hasItem(MY_INSTANT_DATE)));

But what I get from JUnit is:

Expected: a collection containing <2018-06-08T11:46:50.292Z> but: was <1528458378.397000000>

How can I map my Instant date to this format?

Jens
  • 67,715
  • 15
  • 98
  • 113
Krzysztof Majewski
  • 2,494
  • 4
  • 27
  • 51

1 Answers1

2

I've found a solution by making a custom Matcher:

class DateEquals extends BaseMatcher<Integer> {

    private final Date expectedValue;

    DateEquals(Date equalArg) {
        expectedValue = equalArg;
    }

    @Override
    public boolean matches(Object item) {
        Long dateTimeMillis = (Long) item;
        return dateTimeMillis.equals(toEpochMillis(expectedValue));
    }

    @Override
    public void describeTo(Description description) {
        description.appendValue(" equals to date: " + expectedValue);
    }
}

Factory for it:

public class CustomMatchersFactory {
    public static Matcher dateEquals(Date date) {
        return is(new DateEquals(date));
    }
}

And usage:

.andExpect(jsonPath("$.content.[*].startDate", dateEquals(MY_INSTANT_DATE)));
Krzysztof Majewski
  • 2,494
  • 4
  • 27
  • 51