使用 Groovy 脚本生成动态 JSON 请求主体并将其传递给 SoapUI 中的 POST API 请求

Generating and passing dynamic JSON request body to a POST API request in SoapUI using Groovy Script

我正在尝试使用 SOAP UI 为 API 自动化生成动态 JSON 请求主体。我正在使用 groovy 脚本来做同样的事情。 我无法将动态生成的 属性 值传递到请求中的 JSON 主体。有人可以帮忙吗?

我的Groovy脚本

import java.util.Random

//generating random values
Random rand = new Random()
String brandName = "BrandName" + rand.nextInt(100000)
String pageTitle = "BrandPageTitle" + rand.nextInt(100000)

//setting test case properties
testRunner.testCase.setPropertyValue("name", brandName);
testRunner.testCase.setPropertyValue("page_title", pageTitle);

这是我的 JSON POST 请求正文。我不确定下面 JSON 中访问变量的方式是否正确

{
  "name": "${brandName}",
  "page_title": "${pageTitle}"
}

这个我也试过了。 'POSTCreateNewBrand' 是我的测试用例名称,'name' 是 property_name

{
  "name": "${#POSTCreateNewBrand#name}",
  "page_title": "${#POSTCreateNewBrand#page_title}"
}

当我 运行 我的测试时,我发现名称字段没有作为请求正文的一部分提供,并看到以下错误

<errors>
   <error>
      <status>400</status>
      <message>The required field 'name' was not supplied.</message>
   </error>
</errors>

要在 TestCase 级别使用属性,不必使用 TestCase 名称,而是直接使用 #TestCase# 常量,后跟您的 属性 名称,如下所示:

{
  "name": "${#TestCase#name}",
  "page_title": "${#TestCase#page_title}"
}

此外,ProjectTestSuite等也是如此; TestStep 级别的名称,来自 SOAPUI documentation:

#Project# - references a Project property(Reference properties across a particular SoapUI project)

#TestSuite# - references a TestSuite property in the containing TestSuite

#TestCase# - references a TestCase property in the containing TestCase

#MockService# - references a MockService property in the containing MockService

#Global# - references a global property. Found in File>Preferences>Global Properties tab. Reference properties across all projects

#System# - references a system property. Found in Help>System properties.

#Env# - references an environment variable

[TestStep name]# - references a TestStep property

希望这对您有所帮助,