Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
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"() {
  def request = """
    "assessmentTopic" : "$assessmentTopic",
    "assessmentSubTopic" : "$assessmentSubTopic",
    "duration" : "$duration",
    "assessmentLevel" : "$assessmentLevel"

  def result = mvc.perform(

  MvcResult response = result

  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 Vigges Developer Community for programmer and developer-Open, Learning and Share