kuceram
kuceram

Reputation: 3885

Inject Services in Grails Unit Test

I know that you can simply inject a service in unit test method using:

defineBeans {
   someService(SomeService)
}

But when I need to inject service inside a service (the service someService calls itself another service some2Service). When I run the test with above code I receive:

Message: Cannot invoke method someMethod() on null object

Is it possible to inject a service into a service in the unit test?

Thanks. ;-)

Upvotes: 10

Views: 4568

Answers (2)

ataylor
ataylor

Reputation: 66069

To use spring beans in a unit test you need to do the following:

  • Include all the services and other beans the test depends on in the defineBeans closure.
  • Set the autowire property to true for beans that need to have other beans injected.

For example:

defineBeans {
    someService(SomeService) { bean ->
        bean.autowire = true
    }
    some2Service(Some2Service)
}

Upvotes: 9

allthenutsandbolts
allthenutsandbolts

Reputation: 1523

you can set your member variable which is service by using ref

MyService(MyProvider) {
        userDetailsService = ref("userDetailsService")
        springSecurityService = ref("springSecurityService")
        userService = ref("userService")
    }

Hope that helps

Upvotes: 0

Related Questions