使用 groovy 脚本存储从请求到属性的随机整数

问题描述

我想在请求正文中存储一个调用随机整数,并将其存储在测试用例属性中,以便在下一个请求中将其作为正文参数传递。

例如:
请求1:
id_num = randomNumeric(10)

属性
id_num = 1234567890

请求2:
trfered_IDNum = ${#TestCase#id_num}

解决方法

结构如下,

Project
  |---TestSuite
         |-------TestCase
                   |------RestRequestTestStep1
                   |------RestRequestTestStep2
                   |------GroovyScript

让我们从一些假设开始。

  1. RestRequestTestStep1 响应正文具有以下字段:

                         {"Resp1Field1Key":"Resp1Field1Value","Resp1Field2Key":"Resp1Field2Value"}
    
  2. RestRequestTestStep2 请求正文具有以下字段:

                          {"Resp2Field1Key":"Resp2Field1Value","Resp2Field2Key":"Resp2Field2Value"}
    
  3. 第一个响应中的 Resp1Field1Value 和 Resp1Field2Value 将被替换为第二个请求的 Resp2Field1Value 和 Resp2Field2Value。

  4. RestRequestTestStep2 正文应如下所示,因为我们将替换 testCase 属性中的值,该值将在第一个请求完成后在 groovy 脚本中设置。

    { "Resp2Field1Key":"${#TestCase#Resp2Field1Value}","Resp2Field2Key":"${#TestCase#Resp2Field2Value}" }

The Code..rather Script : groovy 脚本可以放在同一个测试用例下,应该在下面做,

import groovy.json.JsonSlurper

//Substitute with appropriate testSuiteName,testCaseName,testStepName1 and testStepName1 as per the Project Structure you have.

def testSuite = testRunner.testCase.testSuite.project.getTestSuiteByName("testSuiteName")
        def testCase = testSuite.getTestCaseByName("testCaseName")
        def testStep1 = testCase.getTestStepByName("testStepName1")
        def testStep2 = testCase.getTestStepByName("testStepName2")
        
       // Call the first REST Request
       testStep1.run(testRunner,context)       
    
        def response = testStep1.testRequest.response.responseContent
        def jsonSlurper = new JsonSlurper().parseText(response)

       //Assign it to a testCase Property to grab for second Rest Request

         if (jsonSlurper.size() > 0) {
            testCase.setPropertyValue("Resp1Field1Value",Resp1Field1Value)
            testCase.setPropertyValue("Resp1Field2Value",Resp1Field2Value)
            );

       //Call the second Rest Request

       testStep2.run(testRunner,context)       
    
        def response = testStep2.testRequest.response.responseContent
        def jsonSlurper = new JsonSlurper().parseText(response)

     // Perform Validation/assertion as desired
            
,

在同一测试用例中的第二个请求之前,在您的 groovy 脚本中使用这两行

def id_num = (new Random().nextInt(100000000)).toString()
testRunner.testCase.setPropertyValue( "id_num",id_num  )
log.info id_num

enter image description here

现在,由于您已在soap步骤中将值保存在测试用例属性中,因此您可以在同一测试用例中的下一个请求中使用如下所示

${#TestCase#id_num}

enter image description here

这样它会在您运行后自动替换该值。要查看soap UI 中的值替换,您可以查看Raw Tab

在下面检查这个..值被替换了

enter image description here