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

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)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)