Contrary to JUnit, where you have to declare field variable static and assign value to it in
@BeforeClass
public static void setupClass()
so it was initialized just once per test suite (not each method), in Spock you may use instance field variable and annotate it with @Shared
.
Consider the following example:
class SharedTestSpec extends spock.lang.Specification {
@Shared
def shared = shared()
def shared() {
"I came from ${this.class.simpleName}"
}
def 'Test one'() {
given:
println("test one, shared: $shared")
expect: true
}
def 'Test two'() {
given:
println("test two, shared: $shared")
expect: true
}
}
class SubclassSpec extends SharedTestSpec {
@Override
def shared() {
println("They've got me!")
"I came from ${this.class.simpleName}"
}
}
Running SubclassSpec gives you the following output:
test one, shared: I came from SubclassSpec
test two, shared: I came from SubclassSpec
They've got me!
Can't explain the print order though, but that's due to AST.
@Shared
better shows your intent – Isobelisocheim