Search code examples
androidokhttpmockserver

Okhttp mock server is not working on API 28 and above simulator


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);
        }
    }
}

Solution

  • 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.