soapui + groovy 接口自动化测试 第七章

野怪资源,保证发育!

1.解析Json数据脚本

import groovy.json.JsonSlurper
def xresponse = testRunner.testCase.testSteps["getPlans"].testRequest.response.contentAsString
def slurper = new JsonSlurper()
def re = slurper.parseText(xresponse)

例:Json格式

{
    "a": "b",
    "c": "d",
    "e": "f",
    "g": [
        {
            "h": "k",
            "l": "m"
        }
    ]
}

groovy读取json的方式很简单,re.c读取c对应的值/re.g.h读取h对应的值

2.步骤跳转脚本

testRunner.gotoStepByName("Step2") 跳转到指定步骤

testRunner.runTestStepByName("Step2") 运行指定步骤或脚本

3.获取response中header值,并设置到下一个请求header中

示例为,获取response-header中session的值(因为seesion值有很多数据需要截取)

首先在下一个请求header部分加入一个参数cookie,然后执行如下脚本就可以了

def teststep = testRunner.testCase.testSteps['login.do']
def setcookie = teststep.testRequest.response.responseHeaders["Set-Cookie"].toString()
def num = setcookie.indexOf(';')
def cookie = setcookie.substring(1, num)
testRunner.testCase.testSuite.setPropertyValue("cookie", cookie)

其他,也可以将获取的session固定的写入TestCase/TestSuite参数位置,在请求header部分添加cookie参数,值部分填入${#TestCase#cookie}的方法来读取

4.设置Request-header部分的参数 

def headers = request.requestHeaders

header.put("X-tokenHeader", "value")

request.requestHeaders = headers

可以理解为将header中参数取出来放在一个Map里边,可以对这个map进行put/remove操作,然后在覆盖回去

5.改变reponse--感觉有点意思,没用过

if(request.response == null)

  return

def content = context.httpResponse.responseContent

content = content.replaceAll("555", "444")

context.heepResponse.responseContent = content

6.数据检查

在Groovy Script中使用equals()/contains()方法进行检查就行了。

soapui提供断言功能,但是在断言环境中不支持testrunner的用法,它支持的是messageExchange(用法和testrunner类似)

Groovy Script环境右上角描述了支持的方法log、context、testRunner

Script Assertion环境右上角描述的支持方法为log、context、messagetExchange

并且断言脚本环境是soapui pro(收费版)才有的功能,既然Groovy Script已经满足了相应功能,所以我们不必去使用断言环境也不必去掌握messageExchange的用法;

 附:官方帮助文档脚本地址 http://www.soapui.org/scripting---properties/tips---tricks.html

下一章将带来如何引入外部脚本及groovy外部脚本示例

原文地址:https://www.cnblogs.com/mayibanjiah/p/4552607.html