Programming for fun and profit

Programming tutorials, problems, solutions. Always with code.

Spock Framework share object reuse


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!


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 ;-)");

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'() {
        heavyObject != null

    def 'should test that'() {
        heavyObject != null

Running whole Specification shows that it works as advertised:

$> gradle cleanTest test --tests com.farenda.solved.SharingElementsTest
:compileJava UP-TO-DATE
:compileGroovy UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE

com.farenda.solved.SharingElementsTest STANDARD_OUT
    Instantiating very costly object...
    ...5 minutes later ;-)


Done! And only one time! :-)

Share with the World!