There are a couple of things going on here. First, MockWebServer.url() resolves the given url against the mock server's base url, it does not set the url. If you want to set the url, you'll need to pass it to the start() method. Generally, you configure your retrofit to call the server's endpoint --

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(server.url("/"))
    // Other builder methods.
    .build();

Second, to get responses from the mock web server, you need to enqueue the expected responses as MockResponses. Otherwise it doesn't know what to send back. Do something like the following before making your request --

server.enqueue(new MockResponse().setBody("Success!"));

You'll need to build your response to mirror the expected response.

See the README for some more examples.

Answer from iagreen on Stack Overflow
🌐
Google
android.googlesource.com › platform › external › okhttp › + › master › mockwebserver › README.md
MockWebServer
MockWebServer server = new MockWebServer(); // Schedule some responses. server.enqueue(new MockResponse().setBody("hello, world!")); server.enqueue(new MockResponse().setBody("sup, bra?")); server.enqueue(new MockResponse().setBody("yo dog")); // Start the server.
🌐
GitHub
github.com › square › okhttp › blob › master › mockwebserver › README.md
okhttp/mockwebserver/README.md at master · square/okhttp
These are lean enough that you can create a new // instance for every unit test. val server = MockWebServer() // Schedule some responses. server.enqueue(MockResponse(body = "hello, world!")) server.enqueue(MockResponse(body = "sup, bra?")) server.enqueue(MockResponse(body = "yo dog")) // Start the server.
Author: square
Discussions

android - How to make MockWebServer work? - Stack Overflow
I am developing an app using the MVP architecture. I am trying to test the Interactors of my app using MockWebServer. Well, I have this test: @RunWith(RobolectricTestRunner::class) @Config(constan... More on stackoverflow.com
🌐 stackoverflow.com
MockWebServer: Enqueue many
For instrumented tests on Android that go through multiple screens to test a user flow, I find myself enqueueing multiple requests so I get the following code: server.enqueue(request1) server.enque... More on github.com
🌐 github.com
1
August 23, 2019
mocking - MockWebServer enqueue by path condition? - Stack Overflow
I'm using MockWebServer from okhttp3 to test my webclient against a mocked external webserver. I want to configure the mock so that responses are returned conditional by path. Like pseudocode: More on stackoverflow.com
🌐 stackoverflow.com
okhttp - How Can I Mock A Specific URL Path? - Stack Overflow
I am using okhttp to mock my http responses during my tests. //Create a mock server mockWebServer.start(8080) mockWebServer.enqueue(MockResponse().setBody("").setResponseCode(HttpURLConne... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Okio
square.github.io › okhttp › 3.x › mockwebserver › okhttp3 › mockwebserver › MockWebServer.html
MockWebServer (MockWebServer 3.14.0 API)
Scripts response to be returned to a request made in sequence. The first request is served by the first enqueued response; the second request by the second enqueued response; and so on.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
rieckpil
rieckpil.de › home › spring framework tutorials › test spring webclient with mockwebserver from okhttp
Test Spring WebClient with MockWebServer from OkHttp - rieckpil
August 27, 2021 - Before we invoke the method of the UsersClient that we want to test, we have to prepare the response. Therefore we can construct a MockResponse matching our needs (body, HTTP header, response code) and queue it using mockWebServer.enqueue().
🌐
Program Creek
programcreek.com › java-api-examples
okhttp3.mockwebserver.MockWebServer#enqueue
@Test public void testAsyncClient() throws Exception { MockWebServer mockWebServer = new MockWebServer(); URI uri = mockWebServer.url("/").uri(); AsyncClient client = RestClientBuilder.newBuilder() .baseUri(uri) .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5, TimeUnit.SECONDS) .build(AsyncClient.class); assertNotNull(client); mockWebServer.enqueue(new MockResponse().setBody("Hello")); mockWebServer.enqueue(new MockResponse().setBody("World")); String combined = client.get().thenCombine(client.get(), (a, b) -> { return a + " " + b; }).toCompletableFuture().get(10, TimeUnit.SECONDS); assertTrue("Hello World".equals(combined) || "World Hello".equals(combined)); }
🌐
GitHub
github.com › square › okhttp › issues › 5392
MockWebServer: Enqueue many · Issue #5392 · lysine-dev/okhttp
August 23, 2019 - server.enqueue(request1) server.enqueue(request2) server.enqueue(request3) For convenience, I propose a method for syntactic sugar: fun MockWebServer.enqueueMany(vararg responses: MockResponse) = responses.forEach { enqueue(it) } Usage: server.enqueueMany(request1, request2, request3) Start by telling us what problem you’re trying to solve.
Author: lysine-dev
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 57196897 › mockwebserver-enqueue-by-path-condition
mocking - MockWebServer enqueue by path condition? - Stack Overflow
mockWebServer.expectPath("/products") .enqueue(new MockResponse().setBody(..)) .expectPath("/items") .enqueue(new MockResponse().setBody(..)); Is that possible? mocking · retrofit2 · okhttp · mockwebserver · Share · Improve this question · Follow · edited Aug 15, 2019 at 14:02 ·
Top answer
1 of 1
4

You could implement a Dispatcher where you add actions to a list, each with a predicate to match the request. Once an action has matched you discard it so the next action can be applied.

public class MyDispatcher implements Dispatcher {
   public static class MyDispatcherEntry {
      private Predicate<RecordedRequest> predicate;
      private Function<RecordedRequest, MockResponse> action;

      // TODO constructor
   }

   private final List<MyDispatcherEntry> entries = new LinkedList<>();

   public void enqueue(String path, MockResponse response) {
      enqueue(req -> req.getPath().equals(path), req -> response);
   }

   public void enqueue(
      Predicate<RecordedRequest> predicate, 
      Function<RecordedRequest, MockResponse> action
   ) {
      entries.add(new MyDispatcherEntry(predicate, action));
   }

   public MockResponse dispatch(RecordedRequest req) {
      for (Iterator<MyDispatcherEntry> it = entries.iterator(); it.hasNext(); ) {
         MyDispatcherEntry entry = it.next();
         if (entry.predicate.test(req)) {
            it.remove(); // discard this action so another can match next time
            return entry.action.apply(req);
         }
      }
      throw new RuntimeException("No matching entries for " + req);
   }

}

Usage

MyDispatcher dispatcher = new MyDispatcher();
dispatcher.enqueue("/query1", new MockResponse().setResponseCode(200).setBody(...));
dispatcher.enqueue("/query2", new MockResponse().setResponseCode(200).setBody(...));
dispatcher.enqueue("/query3", new MockResponse().setResponseCode(502));
dispatcher.enqueue("/query3", new MockResponse().setResponseCode(502));
dispatcher.enqueue("/query3", new MockResponse().setResponseCode(200).setBody(...));
🌐
How to do in Java
howtodoinjava.com › home › java libraries › getting started with mockwebserver and junit
Getting Started with MockWebServer and JUnit
July 11, 2022 - Returning the enqueued responses is not suitable in all conditions. We can use Dispatcher class to devise our own logic to return API responses. In the following example, we are using a dispatcher to match the API URI of the incoming request and then return the response for a matching URI. public class MockWebServerTests ...
🌐
GitHub
github.com › trevorwang › mock-web-server
GitHub - trevorwang/mock-web-server: mirror of MockWebServer · GitHub
MockWebServer server = new MockWebServer(); server.start(); Once you have the server running you will want to get the url of it, so that you can configure your app to connect there · server.url; // will return http://127.0.0.1:8081 server.port; // 8081 server.host; // 127.0.0.1 · Once the server is started, you can queue the responses that you want. The response queue is First In First Out · // Enqueue an empty body with response code 401 server.enqueue(httpCode: 401); // Response code defaults to 200, so this will be a 200 with the given json as the body server.enqueue(body: '{ "message" :
Author: trevorwang
🌐
GitHub
github.com › square › okhttp › tree › master › mockwebserver
okhttp/mockwebserver at main · lysine-dev/okhttp
These are lean enough that you can create a new // instance for every unit test. val server = MockWebServer() // Schedule some responses. server.enqueue(MockResponse(body = "hello, world!")) server.enqueue(MockResponse(body = "sup, bra?")) server.enqueue(MockResponse(body = "yo dog")) // Start the server.
Author: lysine-dev
🌐
Shouldn't Be Hard
arhohuttunen.com › spring-boot-webclient-mockwebserver
Testing Spring Boot WebClient With MockWebServer | Shouldn't Be Hard
May 22, 2021 - To make MockWebServer return canned responses, we can call the enqueue() method that takes a MockResponse as an argument.
🌐
Testim
testim.io › blog › how-to-use-mockwebserver
How to Use MockWebServer to Mock and Test HTTP Calls - AI-driven E2E automation with code-like flexibility for your most resilient tests
March 7, 2025 - Mocking a web server can be done in different applications (Android, Web Apps, etc.). This guide will walk you through how to use the MockWebServer library by developer Square.
🌐
Java Tips
javatips.net › api › com.squareup.okhttp.mockwebserver.mockresponse
Java Examples for com.squareup.okhttp.mockwebserver.MockResponse
@Test(enabled = true) public void testAttachMonitorPolicyToApplicationMock() { HttpUrl serverUrl = mockWebServer.url("/"); mockWebServer.enqueue(new MockResponse().setHeader(HttpHeaders.ACCEPT, MediaType.JSON_UTF_8.toString()).setHeader(HttpHeaders.CONTENT_TYPE, MediaType.JSON_UTF_8.toString())); ...
🌐
Kiprosh Blogs
blog.kiprosh.com › how-to-test-api-response-with-mockwebserver-library
How To Test API Response With MockWebServer Library The Right Way
June 7, 2021 - Create a MockWebServer object · Start the server · Update the BASE_URL with localhost · Add the expected response body in enqueue() Launch the activity ·