【问题标题】:How to mock a method which passes in clazz?如何模拟通过 clazz 的方法?
【发布时间】:2015-07-10 00:38:09
【问题描述】:

我正在尝试为具有 .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 还很陌生,因此我们将不胜感激。我基本上想知道为什么我的单元测试似乎不起作用,以及如何测试这样一个接受类实例参数的函数。
感谢您的帮助!

【问题讨论】:

    标签: unit-testing grails groovy


    【解决方案1】:

    我可能会在测试中对 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).

    【讨论】:

    • 感谢您的回复。不幸的是,我在原始帖子中犯了一个错误,我将 exampleService 作为 AnotherExampleService 中的一个字段,而是使用 exanpleService 扩展了 AnotherExampleService。那我该怎么做呢?
    • 请更新问题,以便清楚问题所在。干杯!
    • 立即查看答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多