JJD*_*JJD 5 android mockwebserver dagger-2 retrofit2 okhttp3
对于Android项目,我使用Dagger 2.6配置了Retrofit 2.1.0和OkHttp 3.4.1,如下面的Dagger模块所示.我的目标是使用@Named限定符支持多个后端.
@Module
public class ApiModule {
private static final String GITHUB_QUALIFIER = "GitHub";
private static final String TWITTER_QUALIFIER = "Twitter";
@Provides
GitHubClient provideGitHubClient(@Named(GITHUB_QUALIFIER) Retrofit retrofit) { /* ... */ }
@Provides
TwitterClient provideTwitterClient(@Named(TWITTER_QUALIFIER) Retrofit retrofit) { /* ... */ }
@Named(GITHUB_QUALIFIER)
@Provides
@Singleton
HttpUrl provideGitHubBaseUrl() { /* ... */ }
@Named(TWITTER_QUALIFIER)
@Provides
@Singleton
HttpUrl provideTwitterBaseUrl() { /* ... */ }
@Named(GITHUB_QUALIFIER)
@Provides
@Singleton
Retrofit getGitHubRetrofit(@Named(GITHUB_QUALIFIER) HttpUrl httpUrl,
OkHttpClient okHttpClient) { /* ... */ }
@Named(TWITTER_QUALIFIER)
@Provides
@Singleton
Retrofit getTwitterRetrofit(@Named(TWITTER_QUALIFIER) HttpUrl httpUrl,
OkHttpClient okHttpClient) { /* ... */ }
private Retrofit getRetrofit(String baseUrl,
OkHttpClient okHttpClient) { /* ... */ }
@Provides
@Singleton
public OkHttpClient provideOkHttpClient() { /* ... */ }
}
Run Code Online (Sandbox Code Playgroud)
我想使用MockWebServer进行测试.但是,我无法找到如何传递MockWebServer的URL,同时支持多个后端:
// From a unit test
mockWebServer = new MockWebServer();
mockWebServer.start();
ApiModule apiModule = new ApiModule();
OkHttpClient okHttpClient = new OkHttpClient.Builder().build();
String url = mockWebServer.url("/").toString();
// Here I cannot pass the URL to Retrofit
Retrofit retrofit = apiModule.provideRetrofit(/* HERE */ okHttpClient);
gitHubClient = apiModule.provideGitHubClient(retrofit);
Run Code Online (Sandbox Code Playgroud)
可以使用 okhttp 拦截器覆盖基本 url。
public final class HostSelectionInterceptor implements Interceptor {
private volatile String mHost;
public void setHost(String host) {
this.mHost = checkNotNull(host);
}
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String host = this.mHost;
if (host != null) {
HttpUrl overriddenBaseUrl = HttpUrl.parse(host);
HttpUrl newUrl = request.url()
.newBuilder()
.host(overriddenBaseUrl.host())
.build();
request = request.newBuilder()
.url(newUrl)
.build();
}
return chain.proceed(request);
}
}
Run Code Online (Sandbox Code Playgroud)
摘自这里: https: //gist.github.com/swankjesse/8571a8207a5815cca1fb
您可以使用此拦截器来提供 MockWebServer url,甚至可以在调试版本的暂存端点之间切换。
| 归档时间: |
|
| 查看次数: |
523 次 |
| 最近记录: |