SoapUiAssert-在groovy中使用字符串作为json路径

0qx6xfy6  于 6个月前  发布在  其他
关注(0)|答案(1)|浏览(74)

我正在使用groovy来自动化SoapUI上的一些测试,并且我还希望以一种方式自动化Assert,即从 *.txt文件中获取字段的名称和值,并检查所需的字段是否与SOapUI响应中的所需值一起存在。
假设我有以下JSON响应:

{
   "path" : {
         "field" : "My Wanted Value"
    }
}

字符串
从我的文本文件中,我将得到以下两个字符串:

path="path.field"
value="My Wanted Value"


我尝试了以下方法:

import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText response

assert json.path==value;


当然,它不起作用。
请问我该怎么做?
谢谢你

shstlldc

shstlldc1#

我认为你的问题是从基于.表示法的路径访问json值,在你的情况下,path.field可以使用以下方法来解决这个问题:

import groovy.json.JsonSlurper

def path='path.field'
def value='My Wanted Value'
def response = '''{
   "path" : {
         "field" : "My Wanted Value"
    }
}'''

def json = new JsonSlurper().parseText response

// split the path an iterate over it step by step to 
// find your value
path.split("\\.").each {
  json = json[it]
}

assert json == value

println json // My Wanted Value
println value // My Wanted Value

字符串
此外,我不确定你是否也在问如何从文件中读取值,如果这也是一个要求,你可以使用ConfigSlurper来做到这一点,假设你有一个名为myProps.txt的文件,其中包含你的内容:

path="path.field"
value="My Wanted Value"


您可以使用以下方法访问它:

import groovy.util.ConfigSlurper

def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
println config.path // path.field
println config.value // My Wanted Value


所有这些(json路径+从文件中读取配置):

import groovy.json.JsonSlurper
import groovy.util.ConfigSlurper

def response = '''{
   "path" : {
         "field" : "My Wanted Value"
    }
}'''

// get the properties from the config file
def urlFile = new File('C:/temp/myProps.txt').toURI().toURL()
def config = new ConfigSlurper().parse(urlFile);
def path=config.path
def value=config.value

def json = new JsonSlurper().parseText response

// split the path an iterate over it step by step
// to find your value
path.split("\\.").each {
 json = json[it]
}

assert json == value

println json // My Wanted Value
println value // My Wanted Value


希望这对你有帮助,

相关问题