What is the best practice to test a Grails Service which depends on another Service? The default mixin TestFor correctly inject the service under test, for eg:
@TestFor(TopService)
class TopServiceTests {
@Test
void testMethod() {
service.method()
}
}
but if my instance of TopService (service) relies on another Service, like InnerService:
class TopService {
def innerService
}
innerService will not be available, dependency injection doesn't seem to fill this variable. How should I proceed?
Integration tests should not use the @TestFor
annotation, they should extend GroovyTestCase
. The test annotations are only for unit tests (and will have bad behavior when used in integration tests, especially the @Mock
annotations). You're seeing one of those bad behaviors now.
If you extend GroovyTestCase
you can then just have
def topService
At the top of your test and it'll get injected with all of it's dependencies injected.
For a unit test case, you'd just want to add new instances of associated services to your service in a setUp
method. Just like:
@TestFor(TopService)
class TopServiceTests {
@Before public void setUp() {
service.otherService = new OtherService()
}
...
I have a CustomerRegistrationServiceTest and my CustomerRegistrationService depends on the PasswordService.
my CustomerRegistrationService just autowires it like normal:
class CustomerRegistrationService {
def passwordService
In my CustomerRegistrationServiceTest I have:
@TestFor(CustomerRegistrationService)
@Mock(Customer)
class CustomerRegistrationServiceTests extends GrailsUnitTestMixin {
void setUp() {
mockService(PasswordService)
}
So when I test the CustomerRegistrationService, it is able to access the PasswordService
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With