Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails integration tests with multiple services

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?

like image 268
Wavyx Avatar asked Jun 13 '12 14:06

Wavyx


2 Answers

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()
    }
    ...
like image 126
Ted Naleid Avatar answered Oct 16 '22 15:10

Ted Naleid


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

like image 34
klogd Avatar answered Oct 16 '22 17:10

klogd