Spring MockMvc - 从 REST 获取 java.time.Instant
Spring MockMvc - getting java.time.Instant from REST
我有一个资源 returns 我有一个 java.time.Instant
属性 的对象。
class X {
...
private Instant startDate;
...
}
我正在测试它:
mockMvc.perform(get("/api/x"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content.[*].startDate").value(hasItem(MY_INSTANT_DATE)));
但是我从 JUnit 得到的是:
Expected: a collection containing <2018-06-08T11:46:50.292Z> but: was <1528458378.397000000>
如何将我的 Instant
日期映射到这种格式?
我通过制作自定义匹配器找到了解决方案:
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);
}
}
它的工厂:
public class CustomMatchersFactory {
public static Matcher dateEquals(Date date) {
return is(new DateEquals(date));
}
}
和用法:
.andExpect(jsonPath("$.content.[*].startDate", dateEquals(MY_INSTANT_DATE)));
我有一个资源 returns 我有一个 java.time.Instant
属性 的对象。
class X {
...
private Instant startDate;
...
}
我正在测试它:
mockMvc.perform(get("/api/x"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.content.[*].startDate").value(hasItem(MY_INSTANT_DATE)));
但是我从 JUnit 得到的是:
Expected: a collection containing <2018-06-08T11:46:50.292Z> but: was <1528458378.397000000>
如何将我的 Instant
日期映射到这种格式?
我通过制作自定义匹配器找到了解决方案:
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);
}
}
它的工厂:
public class CustomMatchersFactory {
public static Matcher dateEquals(Date date) {
return is(new DateEquals(date));
}
}
和用法:
.andExpect(jsonPath("$.content.[*].startDate", dateEquals(MY_INSTANT_DATE)));