简体   繁体   English

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

[英]Spring MockMvc - getting java.time.Instant from REST

I have a resource that returns me an object with java.time.Instant property. 我有一个资源,它返回一个java.time.Instant属性的对象。

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: 但是我从JUnit得到的是:

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

How can I map my Instant date to this format? 如何将我的Instant日期映射到此格式?

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)));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将 Spring 从 2.4.1 升级到 2.6.1,默认不支持 `java.time.Instant` 错误 - Upgrading Spring Boot from 2.4.1 to 2.6.1, getting `java.time.Instant` not supported by default error 获取错误:日期中的from(java.time.Instant)无法应用于(org.threeten.bp.instant) - Getting error: from(java.time.Instant) in Date cannot be applied to (org.threeten.bp.instant) 如何在 Spring Webflux 中将 java.time.Instant 序列化为 ISO 字符串 - How to serialize java.time.Instant as ISO string in Spring Webflux Spring 数据 Elasticsearch - 找不到能够从类型 [java.lang.Long] 转换为类型 [java.time.Instant] 的转换器 - Spring Data Elasticsearch - No converter found capable of converting from type [java.lang.Long] to type [java.time.Instant] java.time.Instant(1.8)是线程安全的吗? - java.time.Instant (1.8) is thread safe? java.time.即时响应 JavaScript 日期 - java.time.Instant response to JavaScript date 逗号无法通过java.time.Instant解析 - Comma fails parsing by java.time.Instant java.time.Instant 是如何计算纳秒的? - How are nanoseconds calculated in java.time.Instant? 将毫秒时间戳反序列化为java.time.Instant - Deserialize millisecond timestamp to java.time.Instant Hibernate-在PostgreSQL中使用java.time.Instant - Hibernate - Using java.time.Instant with PostgreSQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM