2017-04-18 23 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)