我目前有一个Dispatcher
客户端类来进行网络调用。同一客户端也用于单元测试。我想要的是继续使用相同的类,但如果单元测试应用程序只需切换Dispatcher
,以便同步执行所有网络调用并监视结果。
最简单的方法是使用Dagger 2.0
为@Provides
@Named("RealDispatcher")
@Singleton
public Dispatcher provideDispatcher() {
dispatcher = new Dispatcher();
return dispatcher;
}
@Provides
@Named("TestDispatcher")
@Singleton
public Dispatcher provideTestDispatcher() {
dispatcher = new Dispatcher(newSynchronousExecutorService());
return dispatcher;
}
创建一些类似下面的提供方法:
@Singleton
@Component(modules = {RetrofitModule.class})
public interface RetrofitComponent {
void inject(RestClient restClient);
}
组件类:
Dispatcher
难题是,我如何动态切换Dagger 2.0
基于它是否处于“默认”模式或“单元测试”模式。由于注射用Retrofit
中的类型关联是强关联的,我怎样才能不断改变它。
public class RestClient {
private static ApiCall REST_CLIENT;
@Inject
@Named("RealDispatcher")
static Dispatcher dispatcher; ---> need to switch this dynamically
private static void setupRestClient() {
retrofitComponent.inject(this);
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(Level.BODY);
OkHttpClient httpClient = new OkHttpClient();
httpClient.setDispatcher(dispatcher); ---->add dispatcher based on "default" or "unit testing" mode.
httpClient.interceptors().add(logging);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(MainActivity.URL)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
REST_CLIENT = retrofit.create(ApiCall.class);
}
}
客户端设置:
LocationStrategy