如何在Spring Cloud Contract中指定可选的Date属性?

时间:2018-07-13 11:48:38

标签: spring-cloud spring-cloud-contract

我正在尝试使用Spring Cloud Contract。我编写了JSON主体规范,并且需要Date属性为可选。 当我在groovy dsl中指定时:

"processingDate": $(consumer(optional(anyDate())), producer(anyDate())),

失败:

Exception in thread "main" Assertion failed: 

assert testSide ==~ Pattern.compile(stubSide.optionalPattern())
       |        |           |       |        |
       |        false       |       |        (org.springframework.cloud.contract.spec.internal.ClientDslProperty(DslProperty(clientValue:(\d\d\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]), serverValue:2016-06-16)))?
       |                    |       (org.springframework.cloud.contract.spec.internal.ClientDslProperty(DslProperty(clientValue:(\d\d\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]), serverValue:2016-06-16)))?
       |                    (org.springframework.cloud.contract.spec.internal.ClientDslProperty(DslProperty(clientValue:(\d\d\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]), serverValue:2016-06-16)))?
       org.springframework.cloud.contract.spec.internal.ClientDslProperty(DslProperty(clientValue:(\d\d\d\d)-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]), serverValue:2011-01-11))

但是,当将可选与正则表达式一起使用时,它可以工作:

"processingDate": $(consumer(optional(regex(isoDate()))), producer(LocalDateTime.now().format(DateTimeFormatter.ISO_DATE))),

但是显然我不想对每个可选字段使用这种解决方法。

谢谢!

2 个答案:

答案 0 :(得分:0)

似乎可以在regex端添加consumer前缀。只需尝试更改

"processingDate": $(consumer(optional(anyDate())), producer(anyDate())),

"processingDate": $(consumer(optional(regex(anyDate()))), producer(anyDate())),

OR

"processingDate": $(consumer(optional(regex(isoDate()))), producer('2016-06-16')),

有关详情,请参见spring-cloud-contract_optional_parameters

答案 1 :(得分:0)

anyDate()应该像这样直接使用:

"processingDate": ${anyDate()}

如果需要正则表达式,请使用isoDate()。使用org.springframework.cloud.contract.spec.internal.PatternValueDslPropertyorg.springframework.cloud.contract.spec.internal.RegexPatterns的委托是有区别的