Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

how can I combine tests or reuse data in spock

I have a situation where I want to create some data using a post request and then use the result of that post in few other tests, is it possible to do this using spock. From the below I would like to reuse the response (or something thats extracted from it. How can I do that?

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Have you considered making the response you wish to re-use a @Shared variable and initialise it in a setupSpec() method? That is what you usually do if within one specification you wish to share data between feature methods.

See also the 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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...