针对特定异常的Grails Spock测试

针对特定异常的Grails Spock测试,grails,groovy,exception-handling,spock,Grails,Groovy,Exception Handling,Spock,我正在使用Grails2.4.5,努力让Grails描述不同的异常类型 假设我想模仿下面的例子: class FooController { def barService ... def fooAction() { try { barService.someMethod(params) } catch(e) { if (e instanceof FooException) { ... } else if (e instanceof BarException) { ... } else { ..

我正在使用Grails2.4.5,努力让Grails描述不同的异常类型

假设我想模仿下面的例子:

class FooController { 
def barService
...
def fooAction() {
try {
barService.someMethod(params)
} catch(e) {
if (e instanceof FooException) { ... }
else if (e instanceof BarException) { ... }
else { ... }
}
}
考虑到下面的测试

    @TestFor(FooController)
    class FooControllerSpec extends Specification {
    def setup() { controller.barService = Mock(BarService) }
    void "test"() {
      given: "a mock dependency"
      1* controller.barService.someMethod(_) >> { -> throw FooException('foo') }

      when: "the action is requested"
      controller.fooAction()

      then: "expect the FooException behaviour from the action"
      // some behaviour
    }
我希望模拟依赖项闭包中的FooException已经抛出

但是,调试将显示以下内容:

groovy.lang.MissingMethodException: No signature of method: somePackage.FooControllerSpec$_$spock_feature_0_9_closure14.doCall() is applicable for argument types: (java.util.Arrays$ArrayList) values: [[[:]]]

这是虫子吗?有没有办法以上述方式模拟不同的异常?

您需要在
然后
块中指定行为,即:

void "test"() {
  when: "the action is requested"
  controller.fooAction()

  then: "expect the FooException behaviour from the action"
  1 * controller.barService.someMethod(_) >> { -> throw new FooException('foo') }
  response.redirectedUrl == "/some/other/path"
}

问题是,实现中的异常是在操作中处理的。控制器并不是故意让它们冒泡的。如果
catch(e)
转到
throw e
,您可以测试该操作是否引发了异常。不幸的是,这个选项在这里不可用。在发生FooException的情况下它会做什么?通常,类似于重定向到注销。你能做
response.redirectedUrl==“/some/other/path”
?语法对我不起作用,试试,1*controller.barService.someMethod()>{throw new FooException('foo')) }