我如何在 spock 中组合测试或重用数据

how can I combine tests or reuse data in spock

我有一种情况,我想使用 post 请求创建一些数据,然后在其他一些测试中使用该 post 的结果,是否可以使用 spock 来做到这一点。从下面我想重用 response (或从中提取的东西。我该怎么做?

def "AddAssessment valid output case"() {
  given:
  def request = """
  {
    "assessmentTopic" : "$assessmentTopic",
    "assessmentSubTopic" : "$assessmentSubTopic",
    "duration" : "$duration",
    "assessmentLevel" : "$assessmentLevel"
  }
  """

  when:
  def result = mvc.perform(
    MockMvcRequestBuilders
      .post("/assessments/createAssessment")
      .content(request)
      .contentType(MediaType.APPLICATION_JSON)
  )

  then:
  MvcResult response = result
    .andExpect(MockMvcResultMatchers.status().isOk())
    .andExpect(MockMvcResultMatchers.jsonPath('$.*').doesNotExist())
    .andReturn()

  where:
  assessmentTopic | assessmentSubTopic | duration | assessmentLevel
  "Maths"         | "Calculus"         | "120"    | "1"
  "Civils"        | "History"          | "500"    | "4"
  "UPSC"          | "GK"               | "120"    | "5"
  "Chemistry"     | "Elements"         | "120"    | "3"
}

您是否考虑过要重新使用 @Shared 变量并在 setupSpec() 方法中初始化它的响应?如果在一个规范中您希望在特征方法之间共享数据,那么您通常会这样做。

另见 Spock manual, section "Fields"

@Shared res = new VeryExpensiveResource()

Sometimes you need to share an object between feature methods. For example, the object might be very expensive to create, or you might want your feature methods to interact with each other. To achieve this, declare a @Shared field. Again it’s best to initialize the field right at the point of declaration. (Semantically, this is equivalent to initializing the field at the very beginning of the setupSpec() method.)