5

My mock server dispatcher never reaches the override method on simulator runs API 28 and above but it works fine on the other version. Any idea how to trigger it? Or is it just the API version issue?

I'm pointing to localhost:8080. And the okhttp version is 4.2.1.

fun search() {
    sleepSafely(3000)
    mockServer = MockWebServer()
    mockServer.dispatcher = ErrorDispatcher()
    mockServer.start(8080)
    sleepSafely(3000)
    // do the API request
}

public class ErrorDispatcher extends Dispatcher {

    @NotNull
    @Override
    public MockResponse dispatch(RecordedRequest request) {
        // never be triggered
        String path = request.getPath();
        if (path.equalsIgnoreCase("/api/v2/search/person")) {
            return new MockResponse()
                    .setResponseCode(404)
                    .setBody("{"MOCK_KEY": "MOCK_VALUE"}");
        } else if (path.equalsIgnoreCase("/api/v2/search/book")) {
            return new MockResponse()
                    .setResponseCode(404);
        } else {
            return new MockResponse().setResponseCode(404);
        }
    }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Allen
  • 2,979
  • 1
  • 29
  • 34
  • Take a look at the [Example](https://github.com/square/okhttp/tree/master/mockwebserver) of OkHttpMock – Alfaizkhan Oct 03 '19 at 10:04
  • Thanks. I'm following the example. And it does work on the older API version. https://github.com/square/okhttp/tree/master/mockwebserver#dispatcher – Allen Oct 03 '19 at 10:10

2 Answers2

4

I believe this is because Android API 28+ no longer supports cleartext HTTP traffic and the MockWebServer operates on HTTP.

A user commented on this issue suggesting to add android:usesCleartextTraffic="true" to your test manifest.

B W
  • 692
  • 1
  • 8
  • 21
1

You're right, OKHttp3 MockServer doesn't work on API 28 and up. I'm using 'com.squareup.okhttp3:mockwebserver:4.0.1', I needed to downgrade my project to 27 in order to get it to work.

Alaa
  • 798
  • 1
  • 12
  • 24
  • Yes, that's painful. I'll probably lunch an issue on the repo. – Allen Oct 23 '19 at 09:32
  • @Allen Did you open an issue on the okhttp repo? I'd be interested to follow it. I have the same problem. – B W Feb 11 '20 at 21:13