You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SoapUI执行测试前修改REST请求JSON的currentTR属性?

在SoapUI 5.7.1中通过Groovy脚本修改REST请求JSON并执行测试步骤

核心实现步骤

  • 调用PowerShell获取目标currentTR时间戳值
  • 遍历测试用例中的REST测试步骤
  • 读取并解析请求的JSON内容
  • 修改指定属性后写回请求
  • 执行测试步骤

完整Groovy脚本示例

// 1. 调用PowerShell获取需要的currentTR时间戳,替换为你的实际命令
def powerShellCmd = 'powershell.exe -Command "(Get-Date).ToUniversalTime() - (Get-Date \"1970-01-01\").ToUniversalTime() | Select-Object -ExpandProperty TotalMilliseconds"'
def process = powerShellCmd.execute()
process.waitFor()
def targetTR = process.in.text.trim().toLong() // 转换为JSON要求的长整型时间戳

// 2. 获取当前测试用例(脚本需放在测试用例级的Groovy步骤中)
def testCase = context.testCase

// 3. 遍历所有测试步骤,仅处理REST类型
testCase.testStepList.each { step ->
    if (step instanceof com.eviware.soapui.impl.wsdl.teststeps.RestTestRequestStep) {
        def restReq = step.testRequest
        
        // 4. 读取原始请求JSON
        def rawJson = restReq.requestContent
        
        // 5. 解析并修改currentTR属性
        def jsonSlurper = new groovy.json.JsonSlurper()
        def reqJson = jsonSlurper.parseText(rawJson)
        
        // 若currentTR在嵌套节点中,需调整路径,比如reqJson.data.currentTR
        reqJson.currentTR = targetTR
        
        // 6. 将修改后的JSON写回请求
        def jsonBuilder = new groovy.json.JsonBuilder(reqJson)
        restReq.requestContent = jsonBuilder.toPrettyString()
        
        // 7. 执行当前测试步骤
        step.run(context, false)
        
        // 可选:打印执行状态用于调试
        log.info "执行步骤: ${step.name},结果: ${step.status}"
    }
}

关键细节说明

  • PowerShell调用:通过execute()执行系统命令,waitFor()等待命令完成,in.text获取输出结果,注意处理多余换行和空格后转换为长整型。
  • 测试步骤过滤:用instanceof判断类型,避免处理非REST类步骤(如Groovy脚本、JDBC步骤等)。
  • JSON操作:使用Groovy内置的JsonSlurper(解析)和JsonBuilder(生成),SoapUI已集成无需额外依赖;若currentTR在JSON嵌套节点中,需调整属性路径。
  • 步骤执行:step.run(context, false)中的false表示不跳过依赖步骤,按需调整为true可跳过依赖。

注意事项

  • 确保REST测试步骤的请求内容为纯JSON格式,而非表单或其他类型。
  • 复杂JSON结构可先通过log.info reqJson打印结构,确认属性路径后再修改。
  • 测试阶段可先单独处理1-2个步骤验证逻辑,再批量处理80个步骤。

内容的提问来源于stack exchange,提问作者Neil Cherry

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 02:06:09