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

Spock - Testing that 2nd call throws exception

我有一个给定某些初始输入的函数,第一次调用应该正常工作,但第二次调用应该抛出自定义异常。相应的 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() 似乎与第一个调用而不是第二个调用匹配。有没有办法在 spock 中正确执行此操作?我被抛弃了一段时间,因为我的 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 Console

试试

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