如何在dius.pact中实现“ or()”方法

时间:2019-10-17 16:38:24

标签: java spring integration-testing pact

我正在写契约测试,我需要一个可变性。

这是我定义价格对象的实际方法:

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()方法,但实际上不知道如何实现。
我该如何实现公约?

1 个答案:

答案 0 :(得分:1)

在这种情况下,我将编写两个Pact测试,并使用provider state告知提供者要生产哪个。

理性

每个单独的契约测试都有许多固定装置。我们将它们称为 P X Y Z O 。这些装置用于做出以下断言:

  1. 使用某些参数 P
  2. 调用使用者代码时
  3. 然后将请求 X 发送给提供商
  4. 提供者处于状态 Y 时,会产生响应 Z
  5. 当使用者收到响应 Z 时,域对象 O 从步骤1返回给调用方。

如果您的测试中有or,则您有两个不同的 Z 值。反过来,您将具有两个不同的 O 值,或者两个不同的 X P 值,或者两个不同的值> Y (或两者),具体取决于 Z 中的类型是否根据请求而变化。

比方说, Z 中的响应根据提供者状态而变化(更简单的情况)。如果您使用or,您的测试现在将像这样

  1. 使用某些参数 P
  2. 调用使用者代码时
  3. 然后将请求 X 发送给提供商
  4. 提供者处于状态 Y-1 时,会生成响应 Z-1 ,或者处于状态 Y-2 它会产生响应 Z-2
  5. 当使用者收到响应 Z-1 时,域对象 O-1 从步骤1返回给调用方,或者如果使用者收到响应 Z -2 ,域对象 O-2 返回给调用方。

这比分成两个测试要复杂得多。

两个测试

测试一个可能类似于:

  1. 使用(无论使用什么参数)调用使用者代码时
  2. 发送了LambdaDslObject的请求
  3. 提供者状态为response is centPrecision时,会产生:
    "value": {
      "type": "centPrecision",
      "currencyCode": "EUR",
      "preciseAmount": 2800,
      "fractionDigits": 2 // <--- is not mandatory in this case
    }
  1. 哪个将适当的域对象返回给调用者。

测试两个可能类似于:

  1. 使用(无论使用什么参数)调用使用者代码时
  2. 发送了LambdaDslObject的请求
  3. 提供者状态为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-并不旨在作为对提供者返回的字段的完整描述。因此,您可以从响应中删除非必填字段。