I need to get the dependencies injected in my domain objects in my tests.
This tests are placed in the test/integration directory and extends from spock.lang.Specification
.
How can I achieve this?
Note: I've seen this post How to inject spring beans into spock test, but it is not related with grails.
Edit:
The dependency I want to get injected is springSecurityService
in my SecUser
subclass called Player
. The method that is failing is the encodePassword()
, which is called in the beforeInsert()
.
I can mock this encodePassword()
method in some tests, but when I want to test my controllers method save()
, I can't mock the Player
that is being created because it all happens inside the controllers method.
After changing to extend IntegrationSpec
, this is my test code:
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
}
}
I'm getting this exception when running grails test-app :spock
:
java.lang.NullPointerException: Cannot get property 'mainContext' on null object
at grails.plugin.spock.IntegrationSpec.$spock_initializeSharedFields(IntegrationSpec.groovy)
And this one when I run the test alone:
| 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
, maybe? Is your grails application running when you run your tests? – Apothegm