Published on February 20, 2025
Mock HTTP request in Java & Kotlin
MockWebServer to simulate HTTP calls in Java & Kotlin
Simulating HTTP Requests in Java and Kotlin
There are times when we need to simulate an HTTP request in our Java tests. In this article, I will show you how to do it.
MockWebServer
MockWebServer is a project created by Square that is available for both Kotlin and Java. In this example, we will use Java.
Adding Dependencies
We will use Maven. Add the following dependency to your pom.xml file:
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>5.0.0-alpha.14</version>
<scope>test</scope>
</dependency>
Additionally, we will use JUnit5 for testing.
Creating a Basic Service
Let’s create a basic service that will make a request to a server.
private final WebClient webClient;
public MyService() {
this.webClient = WebClient.create();
}
public String get(String url) {
return webClient.get()
.uri(url)
.retrieve()
.bodyToMono(String.class)
.block();
}
Creating a Test
Now let’s create a test that will simulate the server’s response.
public static final String RESPONSE = "This is a simulated response";
private MockWebServer mockServer;
private MyService service;
@BeforeEach
void setUp() throws IOException {
this.service = new MyService();
mockServer = new MockWebServer();
mockServer.start();
}
@AfterEach
void tearDown() throws IOException {
mockServer.shutdown();
}
@Test
void get(){
//GIVEN
mockServer.enqueue(new MockResponse().setBody(RESPONSE));
HttpUrl baseUrl = mockServer.url("api/chat");
//WHEN
String result = service.get(baseUrl.toString());
//THEN
assertEquals(RESPONSE, result);
}
Conclusion
MockWebServer is an excellent tool for simulating HTTP requests in Java and Kotlin. It is easy to use and very powerful.