Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Essential Groovy DSLs


[ 46 ]

Fields


Spock test specifications can contain class instance fields, which is a good place to
store fixture objects. It's important to note however that while fields are declared
as class instance fields their values are not shared between feature methods. In the
following example, truth will be reinitialized to false for each feature method:


class ChapterThreeSimpleSpec extends Specification {
def truth = false

void "the truth could not be truer" () {
given: "the unvarnished truth"
truth = true

expect: "its true"
truth
}
}

Sometime, it might be desirable to subvert this feature of Spock and have a field
whose state is preserved between feature methods. The @Shared annotation will
overcome the default Spock behavior for fields and share the value between feature
method executions.


@Shared def truth = false

Fixture methods


Spock provides four special fixture methods that allow setup and cleanup of objects
in the specification. These can be used in combination with fields in our specification
to handle any setup and cleanup required by the specification or the individual
feature methods:



  • setupSpec(): This is called once per test specification, before the first feature
    method is run. This can be used for any specific test initialization required by
    the system under test, but it cannot access any instance fields.

  • cleanupSpec(): This is called once per test specification, after the last feature
    method has been called. Here, we can do any final teardown of services
    required by the test, but we cannot access any instance fields.

  • setup(): This is called before every feature method. It's good practice to
    initialize fixture data in here.

  • cleanup(): This is called after each feature method. We can release any
    resources consumed in setup() here.


http://www.ebook3000.com
Free download pdf