我需要在我的测试中将依赖项注入到域对象中。
这些测试位于test/integration目录下,并扩展自spock.lang.Specification
。
我该如何实现?
注意:我看过这篇帖子如何将spring bean注入到spock测试中, 但它与grails无关。
编辑:
我想要注入的依赖是springSecurityService
,位于我的SecUser
子类中,名为Player
。失败的方法是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