模拟为模拟域类抛出异常

时间:2011-07-19 01:23:49

标签: unit-testing grails groovy mocking

我正在为Grails服务类编写unit tests。服务类使用多个域类。为域类创建模拟就像使用mockDomain方法的魅力一样。甚至可以轻松编写测试域对象是否可以正确保存的代码路径(域验证)。但是,在我的代码中,我还使用try/catch块来处理域对象操作,该块处理异常情况。有没有办法模拟域操作引发异常?这可以通过Mock框架轻松完成,例如MockitothenThrow)或EasyMockandThrow),但我主要是寻找Grails原生的方法。我愿意接受支持Grails测试框架的框架。

1 个答案:

答案 0 :(得分:1)

使用Groovy的元类化很简单。对于这个例子,我会说你的一个域类是Foo。

void testFooThrowsException(){
    def fooInstance = new Foo()
    fooInstance.metaClass.methodToTest = {arg1, arg2->
        throw new CustomException("I'm an exception")
    }

    shouldFail CustomException, {fooInstance.methodToTest("val1", "val2")}
}

一旦修改了实例的元类,该实例将具有完整生命周期的修改行为。 Read more on metaclassing on the Groovy site.这是国际海事组织Groovy最酷的部分之一。