[英]grailsApplication autowiring to spock tests are always null
Spock測試將空值注入grailsApplication中,因為我嘗試自動裝配grails服務和域對象(規范)
代碼(AttackSpec.groovy)
package core
import grails.test.mixin.TestFor
import grails.test.mixin.TestMixin
import grails.test.mixin.support.GrailsUnitTestMixin
import spock.lang.Specification
/**
* See the API for {@link grails.test.mixin.domain.DomainClassUnitTestMixin} for usage instructions
*/
@TestMixin(GrailsUnitTestMixin)
@TestFor(Attack)
class AttackSpec extends Specification {
def grailsApplication
def setup() {
Attack attack = new Attack();
println 'app '+grailsApplication.toString()
}
def cleanup() {
}
void "test something"() {
setup:
println 'app '+grailsApplication.toString()
}
}
產量
log4j:WARN No appenders could be found for logger (org.codehaus.groovy.grails.commons.DefaultGrailsApplication).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
appnull
appnull
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/C:/ops/grails-2.4.4/dist/grails-plugin-log4j-2.4.4.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/C:/ops/grails-2.4.4/lib/org.slf4j/slf4j-simple/jars/slf4j-simple-1.7.5.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
SLF4J: Actual binding is of type [org.slf4j.impl.GrailsSlf4jLoggerFactory]
我嘗試使用顯式@Autowired批注和靜態鍵入,但始終相同。 好像我必須在某個地方給grails應用程序充氣?
聽起來您想運行集成測試而不是單元測試。 將您的課程移到集成測試文件夾下,您可能需要刪除測試課程注釋,因為我認為這些注釋僅用於單元測試。
在單元測試中注入grailsApplication
有什么意義? 如果要設置配置,因為您的被測類: Attack
讀取grails應用程序的值,則可以模擬grailsApplication,如下所示:
def 'test whatever you want to'() {
def attack = new Attack()
attack.grailsApplication = [config: [my: [setting: "myValue"]]] // if attack uses grailsApplication.config.my.setting internally
when:
def setting = attack.getMySetting()
then:
setting == "myValue"
}
或者,如果您想跟蹤對它的訪問,則可以使用真實的Mock。
如果您確實想使用grails環境進行測試,那么是否正確執行了對框架值的訪問(無論出於何種原因),則應該使用集成測試。 從Spock繼承IntegrationSpec的子類會將grailsApplication注入到測試中,因此您可以在Attack
類中設置真實內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.