从 REST 响应代码(SoapUI)获取变量值

Getting variable value from the REST response code(SoapUI)

这是当我 运行 我的 REST 请求时从 TestCase1 得到的响应(如 XML):

<data contentType="text/plain" contentLength="88">
    <![CDATA[{"message":"success","data":{"export_id":"064c1948fe238d892fcda0f87e361400_1467676599"}}]]>
</data>

我想在测试用例 2 中使用 export_id(dynamic) 的值 064c1948fe238d892fcda0f87e361400_1467676599

我怎样才能做到这一点?我尝试使用 属性 传输,但我不确定如何配置。

您的响应很复杂,不仅仅是 xml 使用 属性 传输提取所需值。因为,它包含 cdata 并且它在内部再次包含 json 并且您需要它内部的值。

因此,为了获得该值,需要使用 Groovy Script 测试步骤而不是 Property Transfer 测试步骤。话虽如此,您删除了 属性 传输并在同一个地方有 Groovy 脚本步骤。

Groovy 脚本的内容 放在这里:

/**
* This script reads a response xml string, extracts cdata at the specified xpath
* Then parse that string as Json and extract the required value
**/
import com.eviware.soapui.support.XmlHolder
import net.sf.json.groovy.JsonSlurper
//For testing using fixed value as you mentioned in the question
//However, you can use the dynamic response as well which is coming from the 
//previous step as well if you want
def soapResponse = '''
<data contentType="text/plain" contentLength="88"><![CDATA[{
           "message":"success",
           "data": 
           {
               "export_id":"064c1948fe238d892fcda0f87e361400_1467676599"
           }
      }]]>
</data>'''
def holder = new XmlHolder(soapResponse)
//Extract the data inside of CDATA section from the response
def data = holder.getNodeValue('//*:data')
//Parse the string with JsonSlurper
def json = new JsonSlurper().parseText(data)
log.info json
//Extract the export_id
def exportId =  json.data."export_id"
log.info "Export id : ${exportId}"
//Since you wanted to use the extracted value in another test case,
//Saving the value at test suite level custom property EXPORT_ID
//So that it can be used in any of the test case once the value is set
context.testCase.testSuite.setPropertyValue('EXPORT_ID', exportId)

如何在其他测试用例中使用export_id值?

  • 如果您想在 (REST / SOAP) Test Request 测试步骤中使用该值,那么您可以使用 属性 扩展简单地使用它,即 ${#TestSuite#EXPORT_ID}.
  • 如果要在 Groovy Script 测试步骤中使用该值,则需要使用 log.info context.expand('${#TestSuite#EXPORT_ID}')
  • 获取该值

如何在Groovy脚本中使用动态响应?

如上面脚本的 in-line 注释中所述,我已经展示了如何使用您的示例数据获取所需的值。

但您可能很难每次都在脚本中替换变量 soapRespone 的值,或者您可能还想自动执行这些操作。

在这种情况下,您只需将 def soapResponse 语句替换为以下代码:


//Replace the previous step request test step name in place of "Test Request"
//Where you get the response which needs to be proceed in the groovy script
def soapResponse = context.expand('${Test Request#Response}')