gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:47:17 26 4
gpt4 key购买 nike

我有一个资源可以返回一个具有 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)));

关于java - Spring MockMvc - 从 REST 获取 java.time.Instant,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50759998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com