I'd like to execute some action when Spock test fails. Specifically, take a screenshot. Is it possible? How to do it?
Stubs are fake classes that come with preprogrammed return values. Mocks are fake classes that we can examine after a test has finished and see which methods were run or not. Spock makes a clear distinction between the two as mocks and stubs , as we will see in the sections to follow.
By default, Spock runs tests sequentially with a single thread. As of version 2.0, Spock supports parallel execution based on the JUnit Platform.
Create a listener class
class ExampleListener extends AbstractRunListener {
def void error(ErrorInfo error) {
println "Actual on error logic"
}
}
then add it to each specification using implementation of IGlobalExtension
that is executed for each Spec
class GlobalSpecExtension implements IGlobalExtension {
@Override
void visitSpec(SpecInfo specInfo) {
specInfo.addListener(new ExampleListener())
}
}
and finally create file named org.spockframework.runtime.extension.IGlobalExtension
in your META-INF/services directory
(typically it will be under src/test/resources
if you are using Maven) with the full name of your IGlobalExtension
implementation e.g.
com.example.tests.GlobalSpecExtension
The best way to achieve this is to write a (global or annotation-driven) Spock extension that implements and registers an AbstractRunListener
. For an example, see OptimizeRunOrderExtension. For how to register a global extension, see the IGlobalExtension descriptor.
There isn't much documentation on extensions because the APIs are still subject to change. If you want to play it safe (and can live with some restrictions), you can implement a JUnit Rule instead.
One problem that you may encounter in both cases is that they don't provide access to the current spec instance. If you need this, you may have to use both an AbstractRunListener
(to be notified of the failure) and an IMethodInterceptor
(to get hold of the spec instance), both registered by the same extension. (Shouldn't be this hard, but that's what's currently there.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With