0

我无法使用 PACT DSL.closeObject()来格式化 PACT 交互响应。我正在征求建议以使这项工作正常进行,或者询问是否.closeObject()没有按预期工作?我有一个包含 2 件商品的购物车。当我尝试使用 2 项格式化预期响应时.closeObject(),它不会编译,请参见下面的代码。编译错误在第一行.closeObject()之后".stringMatcher("name","iPhone")。我需要shoppingCartItems在 PACT 文件中创建预期响应的层次结构。PACT DSL 的广告用法.closeObject()可以从此链接中找到,在“匹配地图部分中的任何键” 使用 .closeObject() 的 PACT DSL 示例中

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 响应负载,应类似于带有分层数据的预期 PACT 响应负载

4

1 回答 1

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 包含两个项目,请将数字二作为第二个参数传递,例如.eachLike("shoppingCartItem", 2).

于 2017-04-24T00:39:44.307 回答