如何通过groovy脚本比较soapui中的文件?

时间:2014-04-21 20:48:34

标签: json groovy soapui

我已成功将响应保存到外部文件中 - response.json 现在我需要编写一个groovy脚本来将response.jsonbaseline.json进行比较。

我的查询围绕如何将baseline.json解析为变量,比如说

def File1 = baseline.json

以后我可以通过groovy来比较这两个文件。 这就是我正在做的事情,但是我无法将外部文件存储到变量

我的groovy脚本:

def a = context.expand('${#TestSuite#BaseLineFolder}') + "\\file1.json" //log.info a 
def slurper = new JsonSlurper() 
def File1 = slurper.parseText (a) 

3 个答案:

答案 0 :(得分:1)

我几天前帮朋友解决了同样的问题。她将json响应保存在外部文件中,并希望将其与soapUI中的json响应进行比较。我对她的解决方案是......

import groovy.json.JsonSlurper

def filePath = "c:/storage/json/localJson.json" //change this to your json file
def jsonResp = context.expand('${CitiesJSON - Request 1#Response}') //CitiesJSON - Request 1 is the name of my test request

assert jsonResp.size() > 0, "No Json response received"

//jParser and jFParser are java.util.HashMaps
def jParser = new JsonSlurper().parseText(jsonResp)
def jFParser = new JsonSlurper().parseText(new File(filePath).text)

//verify the size
assert jParser.size() == jFParser.size(), "The two jsons do not have same number of values"

int i = 0

//loop through the json
jParser.each{
    assert it.value.size() == jFParser[it.key].size(), "Json not of same size"

    for(i = 0; i<it.value.size();i++) {
        it.value[i].each{ k, v ->
            log.info "jParser = ${k}:${v}"
            log.info "jFParser = ${k}:"+jFParser[it.key][k][i]
            def jpVal = v
            def jfpVal = jFParser[it.key][k][i]
            assert jpVal == jfpVal, "value not same"
          }
    }
}

答案 1 :(得分:1)

这是一种我们可以比较两个json文件是否相同的方法。它还确定值在哪个节点上不同。

    import groovy.json.JsonSlurper
def filePath = "c:/storage/json/localJson.json" //change this to your json file
def jsonResp = context.expand('${CitiesJSON - Request 1#Response}') //CitiesJSON - Request 1 is the name of my test request

def outputResp = new JsonSlurper().parseText(jsonResp)
def baselineResp = new JsonSlurper().parseText(new File(filePath).text)

baselineResp.each{

    if (!(it.value == outputResp[it.key]))
    {
        log.info ("File Mismatch at : " + it.key)
    }

}

答案 2 :(得分:0)

使用下面给出的参数调用JSON比较方法,

 object.compareJSONResponse(stepRes,filePath,expRes);