PACT DSL .closeObject用于格式化分层,PACT文件交互,响应

时间:2017-04-18 12:37:15

标签: junit pact pact-java

我无法使用PACT DSL .closeObject()来格式化PACT交互响应。我要求提出建议,或者询问.closeObject()是否按预期工作?我有一个包含2件物品的购物车。当我尝试使用.closeObject()格式化预期响应时,有两个项目,它将无法编译,请参阅下面的代码。编译错误发生在.closeObject()行之后的第一个".stringMatcher("name","iPhone")上。我需要在PACT文件预期响应中创建shoppingCartItems的层次结构。 PACT DSL .closeObject()的广告用法可在此链接中找到,“匹配地图部分中的任意键”PACT DSL examples of using .closeObject()

private DslPart respSc6() {
    DslPart body = new PactDslJsonBody()
        .stringMatcher("id", "ShoppingCart_[0-9]*", "ShoppingCart_0")
        .eachLike("shoppingCartItem")               
        .numberValue("quantity", 1)
        .stringMatcher("state","new")
        .object("productOffering")                              
        .stringMatcher("id","IPHONE_7")
        .stringMatcher("name","iPhone")
        .closeObject()
        .numberValue("quantity", 5)
        .stringMatcher("state","new")               
        .object("productOffering")                                              
        .stringMatcher("id","SMSG_GLXY_S8")
        .stringMatcher("name","Samsung_Galaxy_S8")
        .closeObject()              
        .closeObject()
        .closeArray();
    return body;
}

预期的JSON响应有效负载应该看起来像Expected PACT response payload with hierarchical data

1 个答案:

答案 0 :(得分:1)

以下是与您的示例JSON匹配的已更正和带注释的代码。

  private DslPart respSc6() {
    DslPart body = new PactDslJsonBody()
      .stringMatcher("id", "ShoppingCart_[0-9]*", "ShoppingCart_0")
      .eachLike("shoppingCartItem") // Starts an array [1] and an object [2] (like calling .object(...)) and applies it to all items
        .numberValue("quantity", 1)
        .stringMatcher("state", "new") // You are using a simple string as the regex here, so it will only match 'new'
        .object("productOffering") // Start a new object [3]
          .stringMatcher("id", "IPHONE_7") // Again, this regex will only match 'IPHONE_7'
          .stringMatcher("name", "iPhone") // Again, this regex will only match 'iPhone'
        .closeObject() // Close the object started in [3]
      .closeObject() // Close the object started in [2]
      .closeArray(); // Close the array started in [1]
    return body;
  }

您不需要为shoppingCartItem数组提供两个示例对象定义,因为.eachLike匹配器旨在将一个定义应用于数组中的所有项。如果您希望生成的示例JSON包含两个项目,请将数字2作为第二个参数传递,例如.eachLike("shoppingCartItem", 2)