我正在写契约测试,我需要一个可变性。
这是我定义价格对象的实际方法:
private static LambdaDslObject definePrice(LambdaDslObject object) {
return object
.stringType("type") // <--- could be empty or has 2 different values
.stringType("currencyCode", "EUR")
.numberType("centAmount")
.numberType("fractionDigits");
}
但是此价格对象在JSON中可能如下所示:
如果类型为"centPrecision"
或为空:
"value": {
"type": "centPrecision",
"currencyCode": "EUR",
"preciseAmount": 2800,
"fractionDigits": 2 // <--- is not mandatory in this case
}
or
"value": {
"currencyCode": "EUR",
"preciseAmount": 2800,
"fractionDigits": 2 // <--- is not mandatory in this case
}
或类型为"highPrecision"
"value": {
"type": "highPrecision",
"currencyCode": "EUR",
"centAmount": 2800, // <--- is not mandatory in this case
"preciseAmount": 2800,
"fractionDigits": 2
}
所以我需要根据价格类型进行区分。
我找到了这种or()
方法,但实际上不知道如何实现。
我该如何实现公约?
答案 0 :(得分:1)
在这种情况下,我将编写两个Pact测试,并使用provider state告知提供者要生产哪个。
每个单独的契约测试都有许多固定装置。我们将它们称为 P , X , Y , Z 和 O 。这些装置用于做出以下断言:
如果您的测试中有or
,则您有两个不同的 Z 值。反过来,您将具有两个不同的 O 值,或者两个不同的 X 和 P 值,或者两个不同的值> Y (或两者),具体取决于 Z 中的类型是否根据请求而变化。
比方说, Z 中的响应根据提供者状态而变化(更简单的情况)。如果您使用or
,您的测试现在将像这样
这比分成两个测试要复杂得多。
测试一个可能类似于:
LambdaDslObject
的请求response is centPrecision
时,会产生: "value": {
"type": "centPrecision",
"currencyCode": "EUR",
"preciseAmount": 2800,
"fractionDigits": 2 // <--- is not mandatory in this case
}
测试两个可能类似于:
LambdaDslObject
的请求response is highPrecision
时,会产生: "value": {
"type": "highPrecision",
"currencyCode": "EUR",
"centAmount": 2800, // <--- is not mandatory in this case
"preciseAmount": 2800,
"fractionDigits": 2
}
顺便说一句,请记住,您的Pact测试应该describe only the response fields the consumer actually uses-并不旨在作为对提供者返回的字段的完整描述。因此,您可以从响应中删除非必填字段。