Spring MockMvc - 从 REST 获取 java.time.Instant

Krz*_*ski 5 java junit json spring-mvc mockmvc

我有一个资源,它返回一个具有java.time.Instant属性的对象。

class X {
    ...
    private Instant startDate;
    ...
}
Run Code Online (Sandbox Code Playgroud)

我正在测试它:

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

但我从 JUnit 得到的是:

Expected: a collection containing <2018-06-08T11:46:50.292Z> but: was <1528458378.397000000>
Run Code Online (Sandbox Code Playgroud)

如何将我的Instant日期映射为这种格式?

Krz*_*ski 3

我通过制作自定义匹配器找到了解决方案:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

它的工厂:

public class CustomMatchersFactory {
    public static Matcher dateEquals(Date date) {
        return is(new DateEquals(date));
    }
}
Run Code Online (Sandbox Code Playgroud)

及用法:

.andExpect(jsonPath("$.content.[*].startDate", dateEquals(MY_INSTANT_DATE)));
Run Code Online (Sandbox Code Playgroud)