Take some action when Spock test fails

I would like to perform some action when the Spock test fails. In particular, take a screenshot. Is it possible? How to do it?

+7
source share
4 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 the implementation of IGlobalExtension , which runs for each Spec

 class GlobalSpecExtension implements IGlobalExtension { @Override void visitSpec(SpecInfo specInfo) { specInfo.addListener(new ExampleListener()) } } 

and finally create a file called org.spockframework.runtime.extension.IGlobalExtension in the META-INF/services directory (usually it will be under src/test/resources if you use Maven) with the full name of the implementation of IGlobalExtension , for example.

 com.example.tests.GlobalSpecExtension 
+9
source

The best way to achieve this is to write a (global or annotative) Spock extension that implements and registers AbstractRunListener . For example, see OptimizeRunOrderExtension . For how to register a global extension, see the IGlobalExtension Descriptor .

There is not enough documentation on extensions because the APIs are still subject to change. If you want to play it safely (and you can live with some restrictions), you can use the JUnit rule instead.

One of the problems you may encounter in both cases is that they do not provide access to the current instance of the instance. If you need this, you may have to use both AbstractRunListener (for error notification) and IMethodInterceptor (to get an instance of spec), both registered with the same extension. (It should not be so difficult, but what is currently there.)

+3
source

I managed to do it as follows:

 class ExampleTest extends GebSpec{ static boolean success = false def setup(){ success = false } def cleanup(){ assert success == true, someAction() } def someAction(){ } def "TestCase"(){ expect: /*What you expect here*/ (success = true) != null } } 

Before each test case, "success" is set with the false (false) method with the setup () method. At the end of each test case, you add the operator "(success = true)! = Null". Therefore, "success" will be true only if the test case passes. After each test case, the cleanup () method will check for true success. If this is not called someAction () method.

+3
source

I can't push or comment on user3074543's answer, but it's easier than creating an extension. I want it easy. Therefore, I abbreviated the user a little * (I do not mean single-line methods). You can make logic simpler by writing failure rather than success, and reduce the input using the done () helper.

 class Test extends spock.lang.Specification { def fail def setup(){ fail = true } def done(){ !(fail = false) } def cleanup(){ fail && doStuffWhenFail() } def 'test things'(){ expect: stuff done() } } 
0
source

All Articles