如何在使用MockWebServer

时间:2016-08-02 16:08:07

标签: android retrofit2 dagger-2 okhttp3 mockwebserver

对于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() { /* ... */ }

}

我想使用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);

1 个答案:

答案 0 :(得分:0)

可以使用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);
    }
}

从这里采取:https://gist.github.com/swankjesse/8571a8207a5815cca1fb

您可以使用此拦截器来提供MockWebServer URL,甚至可以在暂存端点之间切换以进行调试构建。