2017-10-09 71 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根据您的描述固定数据,看看它的工作比较。