我不喜欢使用在 android 上运行缓慢的反射。我们大多数人都为依赖注入设置了 dagger2。我为测试设置了一个测试组件。以下是获取应用模式(测试或正常)的简要方法:
创建一个枚举:
public enum ApplicationMode {
NORMAL,TESTING;
}
和一个普通的 AppModule:
@Module
public class AppModule {
@Provides
public ApplicationMode provideApplicationMode(){
return ApplicationMode.NORMAL;
}
}
创建一个像我一样的测试运行器:
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);
}
}
不要忘记像这样在 gradle 中声明它:
defaultConfig {
testInstrumentationRunner "com.mobile.pomelo.base.PomeloTestRunner"
}
现在创建一个 AppModule 的子类,其重写方法看起来与此完全一样,并且不要将其标记为类定义上方的模块:
public class TestAppModule extends AppModule{
public TestAppModule(Application application) {
super(application);
}
@Override
public ApplicationMode provideApplicationMode(){
return ApplicationMode.TESTING; //notice we are testing here
}
}
现在在您在自定义测试运行器中声明的 MyTestApplication 类中声明了以下内容:
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)) //notice we pass in our Test appModule here that we subclassed which has a ApplicationMode set to testing
.build();
}
}
现在要使用它,只需将其注入生产代码中,如下所示:
@Inject
ApplicationMode appMode;
因此,当您运行 espresso 测试时,它将测试枚举,但在生产代码中,它将是普通枚举。
ps 不是必需的,但如果您需要查看我的生产匕首如何构建图形并在应用程序子类中声明:
protected AppComponent initDagger(Application application) {
return DaggerAppComponent.builder()
.appModule(new AppModule(application))
.build();
}