【发布时间】:2018-11-11 15:33:08
【问题描述】:
我想测试一个字段为 java.time.Instant 类型的合同。但并非所有 Instant 实例都按我所期望的 spring-cloud-contract 处理。给定以下简单合约:
Contract.make {
description("Get a version")
request {
method 'GET'
url '/config/version'
headers {
contentType(applicationJson())
}
}
response {
status 200
body(
nr: 42,
creationDate: producer(anyIso8601WithOffset())
)
headers {
contentType(applicationJson())
}
}
}
还有这个服务实现:
@RestController
public class VersionController {
@GetMapping(path = "/version")
public ResponseEntity<Version> getCurrentVersion() {
return ResponseEntity.ok(new Version(42, Instant.ofEpochMilli(0)));
}
}
执行 gradle 测试工作正常。但是,如果我用 Instant.now() 替换 Instant,我的提供程序测试将失败,并显示
java.lang.IllegalStateException: Parsed JSON [{"nr":42,"creationDate":"2018-11-11T15:28:26.958284Z"}] doesn't match the JSON path [$[?(@.['creationDate'] =~ /([0-9]{4})-(1[0-2]|0[1-9])-(3[01]|0[1-9]|[12][0-9])T(2[0-3]|[01][0-9]):([0-5][0-9]):([0-5][0-9])(\.\d{3})?(Z|[+-][01]\d:[0-5]\d)/)]]
这是可以理解的,因为 Instant.now() 会生成一个 Instant,其字符串表示确实与 anyIso8601WithOffset() 模式不匹配。但这是为什么呢?为什么 Instant 的表示方式不同,我该如何描述在任何时刻都有效的合约?
【问题讨论】:
标签: json testing spring-cloud-contract java.time.instant