SoapUi 断言 - 使用字符串作为 groovy 的 json 路径

问题描述 投票:0回答:2

我正在使用 groovy 自动化 SoapUI 上的一些测试,并且我还想以某种方式自动化断言,我将从 *.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;

但是这当然行不通。

知道我该如何完成它吗?

谢谢你

json string groovy soapui assertions
2个回答
2
投票

我认为你的问题是从基于

.
表示法的路径访问 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

希望这有帮助,


0
投票

请查看有关使用 Groovy arse a JSON Response 的 SoapUI 文章。

致以诚挚的问候!

© www.soinside.com 2019 - 2024. All rights reserved.