unit-testing - 具有注入(inject)服务的单元测试抽象类

标签 unit-testing grails dependency-injection abstract-class spock

我的应用程序有一组子类,它们都扩展了某个基类。

BaseClass.groovy

abstract class Base {

    def beforeInsert() {
        userCreated = springSecurityService.currentUser
    }

    /* other stuff */

}

ConcreteClass.groovy
class Concrete extends Base {

    /* stuff, doesn't matter */

}

我正在编写一个必须实例化几个具体的测试:

RelatedServiceSpec.groovy
def "under x circumstances, check for all instances that meet y criteria"() {

  setup: "create 3 concrete classes"
     (1..3).each { new Concrete(a: 'yes').save(validate: false) }

    /* and then the actual test ... */

}

当我保存实例时出现问题,因为 springSecurityServiceBaseClass .我找不到为单元测试 stub 的方法!
  • 我不能@Mock一个抽象类,需要使用defineBeans .
  • Base.springSecurityService引发 NPE。
  • Base.metaClass.springSecurityServiceBase.metaClass.static.springSecurityService编译但不工作。
  • 显然你不能覆盖 Grails 中的事件,所以我不能绕过 beforeInsert ,这样就好了。

  • 有人知道如何使用注入(inject)服务对抽象类进行单元测试吗?

    编辑

    我没有想到将服务注入(inject)实现类!我会试一试!

    最佳答案

    如果创建 beforeInsert() 的实现会发生什么?那beforeInsert()调用,然后您在派生类中为您的测试覆盖?我没有尝试过,所以我不知道它是否会起作用,但在制作 Base 之前可能值得一试具体的。

    abstract class Base {
    
        def beforeInsert() {
            beforeInsertImpl()
        }
    
        def beforeInsertImpl() {
            userCreated = springSecurityService.currentUser
        }
    
        /* other stuff */
    }
    

    在测试中:
    setup: "create 3 concrete classes"
         (1..3).each {
             def concrete = new Concrete(a: 'yes')
             concrete.metaClass.beforeInsertImpl { /* do something with userCreated here */}
             concrete.save(validate: false)
         }
    

    关于unit-testing - 具有注入(inject)服务的单元测试抽象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28819621/

    相关文章:

    javascript - 使用 apply、call 或 bind 方法在 JavaScript 中进行依赖注入(inject)

    jquery - Grails:在 Twitter Bootstrap 中包含 JQuery 自动完成功能

    c# - 将参数传递给 IServiceLocator

    angular - 如何有条件地将服务注入(inject)组件?

    php - 在 PHPUnit 中测试包含文件或本地文件

    reactjs - React 模式对话框的内容不可用于使用 mount() 的 enzyme 测试

    c# - 如何提供两个数组作为 DataRow 参数?

    java - 如何测试具有私有(private)方法、字段或内部类的类?

    image - Grails:从应用程序外部提供静态内容

    Grails 简单插件 "not a valid plugin"