我需要在我的測試中獲取注入到我的域對象中的依賴項。在Grails Spock規範測試中注入依賴項
此測試放置在測試/集成目錄中,並從spock.lang.Specification
擴展。
我該如何做到這一點?
注意:我看到這個帖子How to inject spring beans into spock test,但它與grails無關。
編輯:
我想獲得注入的依賴性在我SecUser
子類,稱爲Player
springSecurityService
。失敗的方法是encodePassword()
,在beforeInsert()
中調用該方法。
我可以在一些測試中嘲笑這個encodePassword()
方法,但是當我想測試我的控制器方法save()
,我不能嘲笑正在創建因爲這一切都發生在控制器方法中的Player
。
改變以延長IntegrationSpec
之後,這是我的測試代碼:
package intertigre.test.domain
import intertigre.domain.Fecha;
import intertigre.test.util.DomainFactoryTestService
import grails.plugin.spock.IntegrationSpec
import grails.test.mixin.TestFor
@TestFor(Fecha)
class FechaSpec extends IntegrationSpec{
DomainFactoryTestService domainFactoryTestService = new DomainFactoryTestService()
def 'test'(){
given:
def fecha = new Fecha()
when:
fecha.save()
then:
Fecha.get(1) == fecha
}
}
運行grails test-app :spock
當我得到這個異常:
java.lang.NullPointerException: Cannot get property 'mainContext' on null object
at grails.plugin.spock.IntegrationSpec.$spock_initializeSharedFields(IntegrationSpec.groovy)
而這一次,當我單獨運行測試:
| Failure: intertigre.test.domain.FechaSpec
| java.lang.NullPointerException: Cannot get property 'autowireCapableBeanFactory' on null object
at grails.plugin.spock.IntegrationSpec.setupSpec(IntegrationSpec.groovy:47)
| Failure: intertigre.test.domain.FechaSpec
| java.lang.NullPointerException: Cannot invoke method isActive() on null object
at grails.test.mixin.support.GrailsUnitTestMixin.shutdownApplicationContext(GrailsUnitTestMixin.groovy:232)
at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:176)
at org.spockframework.runtime.extension.builtin.JUnitFixtureMethodsExtension$FixtureType$FixtureMethodInterceptor.intercept(JUnitFixtureMethodsExtension.java:145)
at org.spockframework.runtime.extension.MethodInvocation.proceed(MethodInvocation.java:84)
at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:176)
'@ AutoWired',也許?運行測試時,您的Grails應用程序是否正在運行? – Will 2012-08-13 11:55:02
也許這是嘲笑這些依賴的更好的主意?什麼依賴不被注入?寫一些示例代碼來顯示問題。 – 2012-08-13 12:59:40
我從來沒有嘗試過在Grails中使用@Autowired,我會嘗試一下。 我在運行測試時沒有運行該應用程序。 – 2012-08-13 15:39:41