2017-04-18 70 views
0

我无法使用PACT DSL .closeObject()来格式化PACT交互响应。我正在寻求建议,以使这项工作或询问.closeObject()是否按预期工作?我有一个购物车2项。当我尝试使用.closeObject()对2个项目进行预期响应格式化时,它不会编译,请参阅下面的代码。编译错误是在第一个.closeObject()之后,在".stringMatcher("name","iPhone")之后。我需要在PACT文件预期响应中创建一个shoppingCartItems的层次结构。 PACT DSL .closeObject()的标榜使用,可以从这个链接可以发现,在“匹配,地图部分任意键” PACT DSL examples of using .closeObject()PACT DSL .closeObject格式化分层PACT文件交互,响应

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

+0

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

回答

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)