Reputation: 3826
Inside a spock test we want to create a resource and make sure its disposed correctly regardless of the outcome of the test result.
We tried the approach below. But spock is not executing tests when the test code is wrapped inside a closure.
import spock.lang.Specification
class ExampleSpec extends Specification {
def wrapperFunction(Closure cl) {
try {
cl()
} finally {
// do custom stuff
}
}
def "test wrapped in closure"() {
wrapperFunction {
expect:
1 == 1
println "will not execute!"
}
}
}
What is the best approach on creating and disposing a resource inside a spock test.
setup()
and cleanup()
are not viable solutions since creating and disposing should be possible at arbitrary points inside the feature method.
Upvotes: 2
Views: 233
Reputation: 5031
You can use setup
and cleanup
block inside of the test case (feature method) like this:
class ReleaseResourcesSpec extends Specification {
void 'Resources are released'() {
setup:
def stream = new FileInputStream('/etc/hosts')
when:
throw new IllegalStateException('test')
then:
true
cleanup:
stream.close()
println 'stream was closed'
}
}
Code from the cleanup
block is always executed although the test fails or if there is any exception. See the result of the above example:
So it is similar to setup()
and cleanup()
methods but in this case you can have different setup and clean up code for each feature method.
Upvotes: 4