ActiveWeb: mocking injected service

19 views Asked by At

When mocking a service injected into a controller, a service method should return a mocked object, something like that:

public class EmptyInterventionServiceMock implements InterventionService {
    @Override
    public Intervention findByInvoiceNumber(String invoiceNumber, String language) {
        return mockedIntervention(invoiceNumber, language);
    }

    protected Intervention mockedIntervention(String invoiceNumber, String language) {
        return mock(Intervention.class);
    }
}

Is it possible to mock some values to be return by the above mocked object (Intervention) to test fi they should be present in the generated JSON template ?

For example, depending on if Intervention has spare parts, services, states (all of them are just collections of other objects), etc. If so, JSON should contain the corresponding keys: services: [{....}], states: [{}], etc.

It would be nice to get the mocked object in the test and stub its return values. The only way I see to achieve that for the moment is to create a separate Mock service class and inject it in a test class as follows:

public class InterventionsControllerSpec extends ControllerSpec {

    @Before
    public void before() {
        Injector injector = injector().bind(InterventionService.class).to(BaseInterventionServiceMock.class).create();
    }

Where BaseInterventionServiceMock just extends EmptyInterventionServiceMock and stubs some methods return values by overriding its mockedIntervention method:

public class BaseInterventionServiceMock extends EmptyInterventionServiceMock {

    @Override
    protected Intervention mockedIntervention(String invoiceNumber, String language) {
        Intervention intervention = mock(Intervention.class);
        when(intervention.getString("ITV_DOCUMENT_NUMBER")).thenReturn("123");
        when(intervention.getString("ITV_INVOICE")).thenReturn(invoiceNumber);
...
etc.

As it is far from ideal, I wonder if there is a DRYer way to do that ?

Thank you.

1

There are 1 answers

1
ipolevoy On

You are not missing anything. Your assumptions are correct. Creating a mock subclass of a service is how we do the testing. If you want a more elegant way, you can submit a proposal for consideration: https://github.com/javalite/activeweb/issues for consideration.