【问题标题】:PACT DSL .closeObject to format hierarchical, PACT file interaction, responsePACT DSL .closeObject 用于格式化分层、PACT 文件交互、响应
【发布时间】:2017-04-24 08:39:44
【问题描述】:

我无法使用 PACT DSL .closeObject() 来格式化 PACT 交互响应。我正在征求建议以完成这项工作或询问.closeObject() 是否没有按预期工作?我有一个包含 2 件商品的购物车。当我尝试使用 .closeObject() 格式化预期的响应时,使用 2 个项目,它将无法编译,请参见下面的代码。编译错误出现在第一个.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

【问题讨论】:

  • 编译错误信息到底是什么?看起来您可能多次关闭对象?此外,你有一个结束 closeArray,但你永远不会在任何地方开始一个数组。我建议您改用 JSON 正文字符串匹配器,因为它比使用 DSL 创建对象更简单。

标签: junit pact pact-java


【解决方案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).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    相关资源
    最近更新 更多