5

My app uses dynamic URLs to make web-service calls (on Android). baseUrl is set as empty and we pass Retrofit2 @Url parameters in the service interface:

public interface UserService {  
    @GET
    public Call<ResponseBody> profilePicture(@Url String url);
}

We don't know the host/domain in advance, so MockWebServer is not able to intercept the requests. The call to fetch the initial list of dynamic URLs is made in different screens. One idea is to create a new flavor providing a local data source for URLs to be used, which is my fallback plan.

I am curious if MockWebServer has any other methods to help test such cases and can be limited to test code.

dev
  • 11,071
  • 22
  • 74
  • 122

2 Answers2

3

You could use an OkHttp interceptor to rewrite the hostname and port?

Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128
  • Can you please elaborate? I am looking for a solution that is limited to test code. In order to use an interceptor, I would need to create another flavor, right? – dev Apr 12 '18 at 04:06
  • 1
    You’d need to install the interceptor in tests only. I don’t think you’ll be able to avoid that. – Jesse Wilson Apr 13 '18 at 00:42
  • Thanks! I added another interceptor with a build flavor. – dev Apr 14 '18 at 08:30
0

I was also facing the same kind of issue. When I use MockWebserver in testing I have to change base URL to target mock web server localhost and port. I tried this it is working fine.

private static final Interceptor mRequestInterceptor = new Interceptor() {
                @Override
                public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                    Request request = chain.request();
                    final InetSocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 8080);

                    HttpUrl httpUrl = request.url().newBuilder().scheme("http://").host(address.getHostName()).port(8080)
                            .build();
                    request = request.newBuilder()
                            .url(httpUrl)
                            .build();

                    return chain.proceed(request);
                }
            };

After this base url changes to "http://localhost:8080/"

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
Rkreddy
  • 41
  • 3