在spock测试中,我们想创建一个资源,并确保正确地处置该资源,而不考虑测试结果如何。
我们尝试了以下方法。但是,当测试代码包装在闭包中时,spock不会执行测试。
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!"
}
}
}
在spock测试中创建和配置资源的最佳方法是什么?
[setup()
和cleanup()
是不可行的解决方案,因为在特征方法内部的任意点都应该可以创建和处置。
您可以像这样在测试用例(功能方法)内使用setup
和cleanup
块:
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'
}
}
C0]块中的代码始终会执行,尽管测试失败或有任何异常。请参阅以上示例的结果:cleanup