我需要在我的测试中获取注入到我的域对象中的依赖项。在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