I tried to implement instrumentation test for my android project. In my main project, I used dagger and retrofit and I provide the retrofit from my Module.
This is my Module that provide retrofit:
@Module
public class NetModule {
@Provides
@Singleton
OkHttpClient.Builder provideOkHttpClientBuilder(){
OkHttpClient.Builder okHttp = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
NoCacheInterceptor noCacheInterceptor = new NoCacheInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
if (!okHttp.interceptors().contains(interceptor))
okHttp.addInterceptor(interceptor);
if (!okHttp.interceptors().contains(noCacheInterceptor))
okHttp.addInterceptor(noCacheInterceptor);
return okHttp;
}
@Provides
Retrofit provideRetrofit(OkHttpClient.Builder httpClient){
return new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Constant.BASE_URL)
.client(httpClient.build()).build();
}
}
Then, in my androidTest folder, I created TestModule to provide retrofit with MockWebServer like below:
@Module
public class TestNetModule {
private final MockWebServer mockWebServer;
public TestNetModule() {
mockWebServer = new MockWebServer();
}
@Provides
@Singleton
MockWebServer providerMockWebServer() {
return new MockWebServer();
}
@Provides
@Singleton
OkHttpClient.Builder provideOkHttpClientBuilder(){
OkHttpClient.Builder okHttp = new OkHttpClient.Builder();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
NoCacheInterceptor noCacheInterceptor = new NoCacheInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
if (!okHttp.interceptors().contains(interceptor))
okHttp.addInterceptor(interceptor);
if (!okHttp.interceptors().contains(noCacheInterceptor))
okHttp.addInterceptor(noCacheInterceptor);
return okHttp;
}
@Provides
Retrofit.Builder provideRetrofitBuilder(OkHttpClient.Builder httpClient, MockWebServer mockWebServer){
return new Retrofit.Builder()
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(mockWebServer.url("/").toString())
.client(httpClient.build()).build();
}
}
When I ran my test, I always get error android.os.NetworkOnMainThreadException
at code .baseUrl(mockWebServer.url("/").toString())
. How is the right implementation MockWebServer with retrofit and dagger for test?
Calling mockWebServer.url("/")
starts the server, an action that can't be done on the main thread.
I solved this like so:
@Provides
@Singleton
MockWebServer providerMockWebServer() {
MockWebServer mockWebServer = new MockWebServer()
Thread thread = new Thread() {
@Override
public void run() {
try {
mockWebServer.start();
} catch (IOException e) {
e.printStackTrace();
}
}
};
thread.start();
return mockWebServer;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With