I have a function that given certain initial inputs, the first call should work properly, but the second call should throw a custom exception. The corresponding spock/groovy code looks similar to the following (generalized):
def 'test'() {
given:
def serviceID1 = genarateID()
def serviceID2 = generateID()
serviceUnderTest.foo(serviceID1) // This should be fine.
when:
serviceUnderTest.foo(serviceID2) // This should throw a custom exception
then:
CustomException e = thrown()
//some verification code on e goes here.
}
What... seems to be happening is that the thrown()
seems to be matching up against the first call rather than the second call. Is there a way to properly do this in spock? I was thrown off for a while because my ide was fine with it but gradlew was telling me of failures until I changed my ide to use gradle to run tests, but I'm not sure how to fix what I'm trying to test.
This reproducer works fine and does what you describe you want to test.
import spock.lang.*
class ASpec extends Specification {
def "hello world"() {
given:
def service = new Service()
and:
service.doTheThing("ok")
when:
service.doTheThing("fails")
then:
RuntimeException e = thrown()
}
}
class Service {
int invocations = 0
void doTheThing(String arg) {
if (invocations++ == 1) {
throw new RuntimeException()
}
}
}
Try it in the Groovy Web Console
Unless it is really necessary to test them both in order, I would suggest to split your tests into two, as you are testing two separate things.