Spring Cloud Contract DSL 验证日期格式

Spring Cloud Contract DSL verify date format

如何验证合同中的日期格式?我 运行 不久前遇到一个问题,我的服务继承了一个对象映射器,该映射器将我的服务 returns 的日期格式从毫秒更改为时间戳。我正在尝试编写一份合同来捕捉日期格式的变化。这是我在合同中写的内容:

response {
    status 200
    body(
            time: 1505276760077L
    )
}

这是我在对象映射器中使用的内容:

@Bean
public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());

    /*
    uncommenting this cause DateTime format to change from 
    milliseconds to timestamp
    i.e., 1505276760077 changes to 2017-09-13T04:26:00.077Z
    Either way, the test passes
     */
    // objectMapper.configure(SerializationFeature
               .WRITE_DATES_AS_TIMESTAMPS, false);

    return objectMapper;
}

无论日期的格式如何,测试都会通过。当格式更改时,有什么方法可以使测试失败吗?

如果有帮助,我这里有一个示例项目:https://github.com/rtteal/consumer-driven-contacts-demo

更新:

我尝试更新我的合同以使用正则表达式,但这仍然不会导致我的测试在更改对象映射器时失败。

response {
    status 200
    body(
            time: $(regex('[0-9]{13}'))
    )
}

这是生成测试的相关部分:

assertThatJson(parsedJson).field("['time']").matches("[0-9]{13}");

测试似乎忽略了对象映射器配置。当测试为 运行 时,我是否需要做一些事情来让它拾取对象映射器?

您可以对日期使用正则表达式 (http://cloud.spring.io/spring-cloud-static/Dalston.SR3/#_regular_expressions)。然后将为您生成一个有效日期。您还可以设置 priority 字段的低值(这意味着更高的优先级)。如果您需要为无效日期创建一个单独的合同,您可以做的是为日期创建一个匹配 nonBlank() 值的配对。为 priority 字段设置更高的值(这意味着更低的优先级)。这样,您将拥有 2 个用于验证 2 个行为的相同 URL 的合同。 1) 有效日期,2) 无效日期

更新:

您正在使用独立设置的 MockMvc。这意味着它会忽略您拥有的任何上下文配置。如果您希望将您创建的 bean 考虑在内,请在此处(https://github.com/rtteal/consumer-driven-contacts-demo/blob/master/src/test/java/com/example/DemoBase.java#L17), use the webAppContextSetup method. Check this page - https://piotrminkowski.wordpress.com/2017/04/26/testing-java-microservices/ 例如。