2017-10-09 100 views
1

我用我的SOAP UI腳本看到了一些不尋常的東西。我只是想執行的斷言,即用數據是正確的,所以我寫了這個代碼如下:如何通過groovy訂購json輸出?

import com.eviware.soapui.support.GroovyUtils 
import groovy.json.JsonOutput 
import groovy.json.JsonSlurper 
def response = messageExchange.response.responseContent 
def json = new JsonSlurper().parseText(response) 
def jsonFormat = (response).toString() 

def policies = [ 
    [x: 28, xxx: 41, xxxxx: 1, name: 'Individual 18-50', aaa: true], 
    [x: 31, xxx: 41, xxxxx: 1, name: 'Individual 51-60', aaa: true], 
    [x: 34, xxx: 41, xxxxx: 1, name: 'Individual 61-75', aaa: true], 
    [x: 37, xxx: 41, xxxxx: 1, name: 'Individual 76-85', aaa: false] 
] 

log.warn json.policies 
log.error policies 
assert json.policies == policies 

當我看log.warn和log.error信息,它會顯示不正確的JSON響應因爲它首先顯示「isActive」字段。

log.warn json.policies顯示此:

[{aaa=true, xx=28, xxxxx=1, name=Individual 18-50, xxxx=41}, {aaa=true, x=31, xxxxx=1, name=Individual 51-60, xxx=41}, {aaa=true, x=34, xxxxx=1, name=Individual 61-75, xxx=41}, {aaa=true, x=37, xxxxx=1, name=Individual 76-85, xxx=41}] 

log.error policies顯示此:

[{x=28, xxx=41, xxxxx=1, name=Individual 18-50, aaa=true}, {x=31, xxx=41, xxxxx=1, name=Individual 51-60, aaa=true}, {x=34, xxxx=41, xxxxxx=1, name=Individual 61-75, aaa=true}, {x=37, xxx=41, xxxxx=1, name=Individual 76-85, aaa=false}] 

如何我必須按正確的順序內的json.policies顯示的DTO,使其按照正確的順序顯示爲政策?

另一個不尋常的事情是,我運行了10次測試用例,並且這個斷言檢查的測試步驟已經超過10次。它應該永遠不會通過,就好像你比較最後的DTO作爲policies的結尾,它顯示isActive其中最後一個在json.policies中的活動爲爲真

+0

Json地圖沒有訂單 –

+0

@ oh ok那麼,我可以問一下,它有時會如何通過,並失敗了斷言?有沒有我在代碼中做了不正確的事情? –

+0

因爲有時它會以正確的順序出現,而其他的不是。您不能依賴訂單 –

回答

1

你快要近了。但是,有幾件事要糾正。

  • 你不必轉換json的toString
  • 列表應該在比較之前排序。
  • 並且每個地圖條目在日誌中顯示的順序並不重要,每個地圖都可以進行比較。

這裏是Script Assertion

//Check if the response is empty or not 
assert context.response, 'Response is empty' 

def json = new groovy.json.JsonSlurper().parseText(context.response) 

//Assign the policies from current response; assuming above json contains that; change below statement otherwise. 
def actualPolicies = json.policies 
//Expected Polities 
def expectedPolicies = [ 
    [id: 28, providerId: 41, coverTypeId: 1, name: 'Individual 18-50', isActive: true], 
    [id: 31, providerId: 41, coverTypeId: 1, name: 'Individual 51-60', isActive: true], 
    [id: 34, providerId: 41, coverTypeId: 1, name: 'Individual 61-75', isActive: true], 
    [id: 37, providerId: 41, coverTypeId: 1, name: 'Individual 76-85', isActive: false] 
] 

log.info "List from response $actualPolicies" 
log.info "List from policies $expectedPolicies" 

//Sort the list and compare; each item is a map and using id to compare both 
assert expectedPolicies.sort{it.id} == actualPolicies.sort{it.id}, 'Both policies are not matching' 

您可以快速地在線demo根據您的描述固定數據,看看它的工作比較。