You technically can put try with resources in spock test,
Groovy 3+ supports try..with..resources: ARM Try with resources
and spock pulls Groovy 3:
See https://spockframework.org/
testCompile "org.spockframework:spock-core:2.0-groovy-3.0"
On the other hand, the mockStatic is active only to the moment when it is closed, which does not compose with Spock's blocks. Thus, usage of cleanup block may be preferred
Like a cleanup method, it is used to free any resources used by a feature method, and is run even if (a previous part of) the feature method has produced an exception. As a consequence, a cleanup block must be coded defensively; in the worst case, it must gracefully handle the situation where the first statement in a feature method has thrown an exception, and all local variables still have their default values.
class Test {
static max(int a, int b) {
return Math.max(a, b)
}
}
def "testMockStatic"() {
given:
var mockedStatic = Mockito.mockStatic(Test.class)
mockedStatic.when({ -> Test.max(2, 3) }).thenReturn(10)
expect:
Test.max(2, 3) == 10
cleanup:
mockedStatic?.close()
}
As cleanup block is executed even if exception is thrown, you may have a code that throws before mockStatic - in this case mockedStatic
is null. Spock advises defensive coding for this case:
As a consequence, a cleanup block must be coded defensively; in the worst case, it must gracefully handle the situation where the first statement in a feature method has thrown an exception, and all local variables still have their default values.
Groovy’s safe dereference operator (foo?.bar())
simplifies writing defensive code.