topr topr - 26 days ago 5
Groovy Question

When Spock's @Shared annotation should be preferred over a static field?

There is not much to add, the whole question is in the title.

Consider these two instances of class Foo used in a Spock specification.

@Shared Foo foo1 = new Foo()

static Foo foo2 = new Foo()


Overall, I know the idea behind
@Shared
annotation but I guess it's better to use language features, which in this case would be
static
field.

Are there any specific cases in which one should preferred over the other or it's rather a matter of taste?

Answer

Spock is all about expressiveness and clarity.

Static is a Java keyword that only shows the internals of the class (that this field is the same for all instances)

@Shared is a Spock feature that says to the reader that this variable is the same for all feature methods. It is an instruction specifically for the unit test and makes the unit test more clear for the reader.

The same can be said for the main Spock blocks. If you think about it they do not really change anything on the code.

public void myScenario(){
  int a = 2 + 3;
  assertEquals(5,a);
}

public void "simple addition scenario"(){
  when: "I add two numbers"
    int a = 2 +3

  then: "I expect the correct result"
  a == 5
}

Both unit tests do exactly the same thing technically. The second however is showing more clearly the intention. The when: and then: labels do not really do anything with the code other than clarifying its intent.

So to sum up, @Shared is making the test more readable. (See also @Issue, @Title etc., they exist for the same purpose)