Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute some action when Spock test fails

Tags:

testing

spock

I'd like to execute some action when Spock test fails. Specifically, take a screenshot. Is it possible? How to do it?

like image 322
amorfis Avatar asked May 07 '13 13:05

amorfis


People also ask

What is stubbing in Spock?

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.

Does Spock run tests in parallel?

By default, Spock runs tests sequentially with a single thread. As of version 2.0, Spock supports parallel execution based on the JUnit Platform.


2 Answers

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
like image 88
Tomasz Dziurko Avatar answered Oct 06 '22 09:10

Tomasz Dziurko


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.)

like image 24
Peter Niederwieser Avatar answered Oct 06 '22 08:10

Peter Niederwieser