Problem:
You’ve got some very costly object to instantiate or it just doesn’t change through all the tests and just want to reuse it (for example DateTime object). Spock Framework allows to do it in an easy and readable way. Learn here how!
Solution:
Here’s sample costly class:
package com.farenda.solved; public class VeryCostlyObject { public VeryCostlyObject() { System.out.println("Instantiating very costly object..."); System.out.println("...5 minutes later ;-)"); System.out.println("Done!"); } }
Clearly you don’t want to create a new instance for each test. This can be solved using Spock’s @Shared annotation, like so:
package com.farenda.solved import spock.lang.Shared import spock.lang.Specification class SharingElementsTest extends Specification { // Will be instantiated only once for all the tests! def @Shared heavyObject = new VeryCostlyObject() def 'should test this'() { expect: heavyObject != null } def 'should test that'() { expect: heavyObject != null } }
Running whole Specification shows that it works as advertised:
$> gradle cleanTest test --tests com.farenda.solved.SharingElementsTest :cleanTest :compileJava UP-TO-DATE :compileGroovy UP-TO-DATE :processResources UP-TO-DATE :classes UP-TO-DATE :compileTestJava UP-TO-DATE :compileTestGroovy :processTestResources UP-TO-DATE :testClasses :test com.farenda.solved.SharingElementsTest STANDARD_OUT Instantiating very costly object... ...5 minutes later ;-) Done! BUILD SUCCESSFUL
Done! And only one time! :-)