Spock -测试第二个调用抛出异常



我有一个函数,它给出了某些初始输入,第一次调用应该正常工作,但第二次调用应该抛出一个自定义异常。对应的spock/groovy代码看起来类似于以下(一般化):

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.
}

什么…似乎正在发生的是thrown()似乎与第一次呼叫匹配而不是第二次呼叫。在史波克有没有合适的方法?我被甩了一段时间,因为我的ide很好,但gradlew告诉我失败,直到我改变我的ide使用gradle来运行测试,但我不确定如何修复我想测试的东西。

这个复制器工作得很好,并且做了您想要测试的描述。

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()
}
}
}

在Groovy Web控制台中试试

除非真的有必要按顺序测试它们,否则我建议将您的测试分为两个,因为您正在测试两个独立的东西。

最新更新