[英]Unit test abstract class with injected service
我的應用程序有一組子類,它們都擴展了某個基類。
BaseClass.groovy
abstract class Base {
def beforeInsert() {
userCreated = springSecurityService.currentUser
}
/* other stuff */
}
ConcreteClass.groovy
class Concrete extends Base {
/* stuff, doesn't matter */
}
我正在編寫一個必須實例化幾個Concretes的測試:
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 ... */
}
當我保存實例時會出現問題,因為springSecurityService
在BaseClass
。 我無法找到一種方法來為單元測試存根!
@Mock
一個抽象類,這是使用defineBeans
。 Base.springSecurityService
引發了一個NPE。 Base.metaClass.springSecurityService
和Base.metaClass.static.springSecurityService
編譯但不起作用。 beforeInsert
,這很好。 有人知道如何使用注入的服務對抽象類進行單元測試嗎?
編輯
我沒有想到將服務注入實現類! 我試試吧!
如果您創建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)
}
Concrete.metaClass.getSpringSecurityService = {
return [
getCurrentUser: {
return new User()
}
] as SpringSecurityService
}
你能試試嗎? 當然,這應該在調用new Concrete()之前進行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.