【发布时间】:2012-08-13 04:35:14
【问题描述】:
我需要在我的测试中将依赖项注入到我的域对象中。
这些测试被放置在 test/integration 目录并从spock.lang.Specification扩展。
我怎样才能做到这一点?
注意:我看过这个帖子How to inject spring beans into spock test,但它与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 应用程序是否正在运行? -
也许模拟这些依赖关系更好?没有注入哪些依赖项?编写一些示例代码来显示一个问题。
-
我从未尝试在 Grails 中使用 @Autowired,我会尝试的。运行测试时我没有运行应用程序。
-
我已经用更多数据更新了我的问题,我稍后会添加代码
标签: testing grails groovy dependency-injection spock