我需要在我的测试中得到在我的域对象中注入的依赖项.
此测试放在测试/集成目录中,并从spock.lang.Specification扩展.
我该如何实现?
注意:我看过这篇文章How to inject spring beans into spock test,但它与grails无关.
编辑:
我想要注入的依赖项是SpringSecurityService在我的SecUser子类称为Player.失败的方法是encodePassword(),它在beforeInsert()中调用.
我可以在某些测试中模拟这个encodePassword()方法,但是当我想测试我的控制器方法save()时,我无法模拟正在创建的播放器,因为它们都发生在控制器方法中.
改变扩展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测试应用程序时遇到这个异常: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)
尝试将springSecurityService声明为测试,就像在控制器中一样. Grails应该为你做所有的工作:)
原文链接:https://www.f2er.com/javaschema/281766.html对于集成测试,您可以执行以下操作:
package intertigre.test.domain import intertigre.domain.Fecha; import intertigre.test.util.DomainFactoryTestService import grails.plugin.spock.IntegrationSpec class DomainFactoryTestServiceSpec extends IntegrationSpec{ def domainFactoryTestService // you dont need to create a new instance,it's injected by spring def 'test'(){ given: // ... when: // ... then: // .... }
如果您需要测试一个特定的域对象(作为您的Fecha类),则可能需要进行单元测试,如下所示:
package intertigre.test.domain import intertigre.domain.Fecha import intertigre.test.util.DomainFactoryTestService import grails.test.mixin.TestFor import grails.test.mixin.Mock import spock.lang.Specification @TestFor(Fecha) @Mock([OtherObject1,OtherObject2]) class FechaSpec extends Specification { def domainFactoryTestService // same thing here,if you need the service def 'test'() { given: def fecha = new Fecha() and: def oo1 = new OtherObject1() when: // ... then: // .... }
您也可以使用单元测试来测试服务,这取决于您要测试什么(一类 – 服务或“情况” – 服务使用方式).