I prefer not to use reflection, which runs slowly on android. Most of us have a dagger2 configured for an injection of addiction. I have a test component configured for testing. Below is a brief way to get the application mode (testing or normal):
create enumeration:
public enum ApplicationMode { NORMAL,TESTING; }
and regular AppModule:
@Module public class AppModule { @Provides public ApplicationMode provideApplicationMode(){ return ApplicationMode.NORMAL; } }
create a test runner like me:
public class PomeloTestRunner extends AndroidJUnitRunner { @Override public Application newApplication(ClassLoader cl, String className, Context context) throws InstantiationException, IllegalAccessException, ClassNotFoundException { return super.newApplication(cl, MyTestApplication.class.getName(), context); } }
Remember to declare it in gradle as follows:
defaultConfig { testInstrumentationRunner "com.mobile.pomelo.base.PomeloTestRunner" }
Now create a subclass of AppModule with an override method that will look exactly the same and not mark it as a module above the class definition:
public class TestAppModule extends AppModule{ public TestAppModule(Application application) { super(application); } @Override public ApplicationMode provideApplicationMode(){ return ApplicationMode.TESTING;
now in your MyTestApplication class that you declared in your custom test runner, the following is declared:
public class PomeloTestApplication extends PomeloApplication { @Singleton @Component(modules = {AppModule.class}) public interface TestAppComponent extends AppComponent { } @Override protected AppComponent initDagger(Application application) { return DaggerPomeloTestApplication_TestAppComponent.builder() .appModule(new TestAppModule(application))
Now, to use it, just enter it in production code wherever possible:
@Inject ApplicationMode appMode;
therefore, when your test tests of espresso will check the enumeration, but when in the production code it will be a normal enumeration.
ps is not needed, but if you need to see how my production dagger builds a graph in this way and is declared in a subclass of the application:
protected AppComponent initDagger(Application application) { return DaggerAppComponent.builder() .appModule(new AppModule(application)) .build(); }