Grails的斯波克测试特定异常

Grails的斯波克测试特定异常

问题描述:

我与Grails的2.4.5工作,努力让Grails的划定不同的异常类型。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: [[[:]]] 

这是一个错误?有没有办法以上述方式模拟不同的异常?

您需要在then块,即指定行为:

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" 
} 
+0

的事情是,在执行异常的动作中进行处理。控制器不会冒泡设计。 (catch)(e)'去'抛出e',你可以测试这个动作是否抛出异常。不幸的是,这里没有这个选项。 –

+0

它在FooException中的作用是什么? –

+0

通常情况下,像重定向到注销。 –