lundi 12 septembre 2016

How to Mock an injected object that is not declared in Module?

For a dagger2 module

@Module
public class MyModule {
    @Provides @Singleton public RestService provideRestService() {
        return new RestService();
    }

    @Provides @Singleton public MyPrinter provideMyPrinter() {
        return new MyPrinter();
    }
}

We could have the test module as Test

public class TestModule extends MyModule {
    @Override public MyPrinter provideMyPrinter() {
        return Mockito.mock(MyPrinter.class);
    }

    @Override public RestService provideRestService() {
        return Mockito.mock(RestService.class);
    }
}

However if for a class as below that is not declared in the dagger module...

public class MainService {
    @Inject RestService restService;

    @Inject public MainService(RestService restService) {
        this.restService = restService;
    }
}

How do I create a mock of MainService as above.

Note, I'm not planning to perform test for MainService as per share in http://ift.tt/2cD8hXq, but instead, my MainService is used in another normal class that I wanted to test. e.g.

public class MyClassToTest() {
    @Inject MainService mainService;

    public MyClassToTest() {
        //...
    }

    // ...
}

Aucun commentaire:

Enregistrer un commentaire