Deploying a breadboard service into a domain class for Grails unit test?

I am writing some Spock-based unit tests under Grails 2.1.1. I find it hard to get the springSecurityService injected into my domain object that is used by my device.

This is what I still have

 @Mock([SecUser]) @TestFor(FooService) class FooServiceSpec extends Specification { def "test some stuff"() { given: def mockSecUserService = Mock(SecUserService) mockSecUserService.emailValid(_) >> { true } mockSecUserService.checkUsername(_) >> { null } service.secUserService = mockSecUserService def mockSpringSecurityService = Mock(SpringSecurityService) mockSpringSecurityService.encodePassword(_) >> { 'tester' } // FIXME this needs to be injected somehow def params = [ email: ' unittest@test.com ', username: 'unittester', password: 'tester', password2: 'tester' ] when: def result = service.createUser(params) then: // test results } } 

So what happens is that my service being tested throws a NullPointerException because mockSpringSecruityService is not being injected. The createUser call in my service checks some parameters and then creates the SecUser domain SecUser .

SecUser has the following service introduced in it to support password encoding,

 class SecUser { transient springSecurityService 

What I cannot understand is to implement this service so that it is available to the domain class. I know that there are several messages already related to this topic, but most of them suggest that the test can create an instance of a domain object, but in my case the instance is part of the device under test.

I tried the following instead of FIXME,

 defineBeans { mockSpringSecurityService(SpringSecurityService) { bean -> bean.autowire = true } } 

But as a result, I get the following error:

| groovy L. SpringSecurityService, ...] Possible solutions: wait (), any (), find (), dump (), collect (), Grep ()

Any ideas?

+7
unit-testing testing grails groovy spock
source share
1 answer

What I ended up with work is

 SecUser.metaClass.encodePassword = { null } 

My encodePassword domain object uses the springSecurityService bean method. Therefore, if I understand this correctly, it simply overwrites this method in order to do nothing (the method is invalid).

I would prefer to use metaClass to replace bean code, but my attempt

 SecUser.metaClass.getSpringSecurityService = { mockSpringSecurityService } 

Explodes with NPE when encodePassword tries to use SpringSecurityService.

I feel that this is less than an ideal job, so I would like someone to give a less-wicked answer.

+6
source share

All Articles