如何模拟传递clazz的方法?

时间:2015-07-10 00:38:10

标签: unit-testing grails groovy

我正在尝试为一个接受.class参数的方法编写单元测试。

例如:

ExampleService {
    def myExample(clazz){
        //do stuff and return some object
    }
}

/* How the above function gets used */
AnotherExampleService extends exampleService {


    def blah() {
        def obj = myExample(AnotherClass.class)
    }
}

/* Now I need to test the above blah() function */
AnotherExampleServiceSpec extends Specification {
    def "test blah"() {
        //The following doesn't seem to work
        ExampleService.metaClass.myExample = { def arg1 -> obj }
    }
}

我对Groovy / Grails很新,所以任何帮助都会非常感激。我基本上想知道为什么我的单元测试似乎不起作用,以及如何测试这样一个接受类实例的参数的函数。
谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

我可能会在测试中继承ExampleService。所以它看起来像:

ExampleService {
    def myExample(clazz){
        //do stuff and return some object
    }
}

AnotherExampleService extends ExampleService {
    def exampleService

    def blah() {
        def obj = myExample(AnotherClass)
    }
}

AnotherExampleServiceSpec extends Specification {
    def "test blah"() {
        given:
           AnotherExampleService service = new AnotherExampleService() {
              @Override
              def myExample(clazz){
                 //whatever you want to do
                 return whatEverResult  
              }
        when:
           def result = service.blah (SomeClass)
        then: 
           result
    }
}

正如您所看到的,myExample方法在此处被覆盖以返回一些模拟值,并且没有修改元类:-)为了使Groovy更容易,您可以明确说明输入类型,例如: def myExample(Class clazz)