Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to share setup across multiple tests using the spock framework w/ groovy

Tags:

groovy

spock

I'm new to spock and noticed the setup: step in a specification is scoped local to that specific test. How might I share setup across these fixtures similar to the traditional junit approach?

thank you!

def "setup with spock"() {
    setup:
    def message = new FooMessage()
    def sut = new FooProcessor()
    def builder = Mock(FooBuilder)
    sut.setBuilder(builder)

    when:
    builder.buildFooUsing(_) >> {"bar"}
    def result = sut.process(message)

    then:
    assert result == "bar"
  }
like image 254
JimmyBond00007 Avatar asked Aug 10 '11 12:08

JimmyBond00007


2 Answers

You should use setupSpec() or look at @Shared annotation if you want to share a single object across tests

like image 58
Aravind Yarram Avatar answered Nov 06 '22 11:11

Aravind Yarram


From Spock documentation

1.3.4 Sharing of Objects between Iterations

In order to share an object between iterations, it has to be kept in a @Shared or static field.

Note: Only @Shared and static variables can be accessed from within a where: block.

Note that such objects will also be shared with other methods. There is currently no good way to share an object just between iterations of the same method. If you consider this a problem, consider putting each method into a separate spec, all of which can be kept in the same file. This achieves better isolation at the cost of some boilerplate code.

like image 25
Xelian Avatar answered Nov 06 '22 09:11

Xelian