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

2

6

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"
  }
Zigzagger answered 10/8, 2011 at 12:41 Comment(0)
G
4

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

Gobo answered 10/8, 2011 at 12:51 Comment(0)
S
2

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.

Sarre answered 10/3, 2015 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.