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

如何在ReadyAPI/SoapUI中通过Groovy测试用例级动态更新Resource值

我之前在ReadyAPI里处理过类似的场景,给你几个完全针对测试用例级别的Groovy解决方案,绝对不会影响项目里的其他测试用例:

测试用例级URL动态替换方案(ReadyAPI + Groovy)

方法1:测试用例Setup脚本批量修改请求URL

这个方法适合给当前测试用例下的所有请求统一替换URL参数,每次运行用例前自动生效,完全不干扰其他用例。

操作步骤:

  1. 先给你的测试用例添加自定义属性:比如targetUserId和targetCustomerId,用来存放要替换的101和99的值(后续可以配合数据源循环多组测试值)。
  2. 打开测试用例的Setup Script,粘贴以下Groovy代码:
// 从测试用例自定义属性中获取要替换的值
def userId = testCase.getPropertyValue("targetUserId")
def customerId = testCase.getPropertyValue("targetCustomerId")

// 遍历当前测试用例下的所有请求步骤
testCase.testSteps.each { step ->
    // 判断是否是HTTP请求步骤
    if (step instanceof com.eviware.soapui.impl.wsdl.teststeps.WsdlRequestTestStep) {
        def originalUrl = step.getHttpRequest().getUrl()
        // 替换路径中的固定值为变量
        def newPath = originalUrl.getPath().replaceAll("101", userId).replaceAll("99", customerId)
        // 重新构造并设置新URL
        def newUrl = new URL(originalUrl.getProtocol(), originalUrl.getHost(), originalUrl.getPort(), newPath)
        step.getHttpRequest().setUrl(newUrl)
    }
}

这样每次运行该测试用例时,都会自动把用例内所有请求的testing/101/getCustomer/99路径替换成testing/${userId}/getCustomer/${customerId},而且只对当前用例生效。

方法2:单个请求PreScript精准修改

如果只需要修改某一个特定请求的URL,不想批量改,可以在目标请求的PreScript里写代码,灵活性更高:

// 从测试用例属性或数据源获取变量值
def userId = testCase.getPropertyValue("targetUserId")
def customerId = testCase.getPropertyValue("targetCustomerId")

// 获取当前请求的URL对象
def requestUrl = context.testStep.getHttpRequest().getUrl()
// 直接构建新的资源路径
def newPath = "/testing/${userId}/getCustomer/${customerId}"
// 设置新URL
context.testStep.getHttpRequest().setUrl(new URL(requestUrl.getProtocol(), requestUrl.getHost(), requestUrl.getPort(), newPath))

这种方式只会修改当前请求的URL,完全独立于其他测试用例和请求。

配合数据源实现多组值循环测试

如果要一次性运行多组userId和customerId的测试:

  • 给测试用例添加一个数据源(比如Excel、CSV),把所有测试值按行存入。
  • 设置测试用例的循环选项为“数据源行数”,这样每次循环都会自动从数据源取新的targetUserId和targetCustomerId值,再通过上面的Groovy代码自动替换URL。

这些方案都是测试用例级别的修改,不会改动项目的原始请求配置,完美适配你每个测试用例对应不同URL的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:48:52