如何使用Groovy在单个测试套件中配置两个不同端点?
解决不同测试用例设置对应环境专属端点的问题
我来帮你搞定这个需求——你现在的核心痛点是从「所有用例统一端点」变成「不同用例对应不同端点」,那关键就是要建立环境-测试用例-端点的对应关系,下面给你两种实用的实现方式:
方案1:配置映射表(推荐,灵活易维护)
这种方式把所有环境和测试用例的端点配置集中管理,后续新增用例或环境都只需要修改映射表,非常直观:
// 第一步:定义环境与各测试用例端点的映射关系 def envEndpointMap = [ 'UAT1': [ 'testcase1': 'http://uat1-endpoint1.example.com', 'testcase2': 'http://uat1-endpoint2.example.com', // 可以继续添加更多测试用例的端点配置 ], 'UAT2': [ 'testcase1': 'http://uat2-endpoint1.example.com', 'testcase2': 'http://uat2-endpoint2.example.com', ], 'UAT3': [ 'testcase1': 'http://uat3-endpoint1.example.com', 'testcase2': 'http://uat3-endpoint2.example.com', ] ] // 第二步:获取用户选择的环境 def result = com.eviware.soapui.support.UISupport.prompt("Please select the environment", "Environment", ['UAT1','UAT2','UAT3']) if (!result) { // 用户取消选择,直接退出脚本 return } // 第三步:根据选择的环境,获取对应测试用例的端点配置 def caseEndpointMap = envEndpointMap[result] if (!caseEndpointMap) { com.eviware.soapui.support.UISupport.showInfoMessage("No endpoint configuration found for environment: ${result}", "Error") return } // 第四步:遍历所有测试用例,设置对应端点 def testcases = testSuite.getTestCaseList() testcases.each { testcase -> def caseName = testcase.getName() // 检查当前测试用例是否有对应的端点配置 if (caseEndpointMap.containsKey(caseName)) { def targetEndpoint = caseEndpointMap[caseName] // 给当前测试用例下的所有测试步骤设置端点 testcase.getTestStepList().each { teststep -> teststep.setPropertyValue('endpoint', targetEndpoint) } } else { // 可选:对未配置的用例给出提示 com.eviware.soapui.support.UISupport.showInfoMessage("No endpoint configured for test case: ${caseName} in ${result}", "Warning") } }
方案优势:
- 配置集中,所有端点规则一目了然,修改维护成本低
- 容错性强,处理了用户取消选择、环境无配置、用例无配置的场景
- 扩展性好,新增测试用例或环境时,只需要在映射表中添加对应条目
方案2:基于命名规则自动生成(适合规范命名场景)
如果你的测试用例命名有固定规律(比如testcase1对应endpoint1,testcase2对应endpoint2),可以用这种更简洁的方式,不用维护映射表:
// 获取用户选择的环境 def result = com.eviware.soapui.support.UISupport.prompt("Please select the environment", "Environment", ['UAT1','UAT2','UAT3']) if (!result) return // 遍历测试用例,根据命名规则生成对应端点 def testcases = testSuite.getTestCaseList() testcases.each { testcase -> def caseName = testcase.getName() // 从测试用例名称中提取数字部分(比如从testcase1中拿到1) def endpointSuffix = caseName.replaceAll('testcase', '') // 拼接生成对应环境的端点 def targetEndpoint = "http://${result}-endpoint${endpointSuffix}.example.com" // 给当前测试用例下的所有测试步骤设置端点 testcase.getTestStepList().each { teststep -> teststep.setPropertyValue('endpoint', targetEndpoint) } }
方案优势:
- 代码更简洁,无需维护额外的配置映射
- 适合测试用例和端点命名高度规范的场景
内容的提问来源于stack exchange,提问作者coolboy back to blast
相关产品推荐
相关产品推荐

