GitHub
github.com › square › okhttp › tree › master › mockwebserver
okhttp/mockwebserver at main · lysine-dev/okhttp
public void test() throws Exception { // Create a MockWebServer. These are lean enough that you can create a new // instance for every unit test. MockWebServer server = new MockWebServer(); // Schedule some responses.
Author: lysine-dev
Medium
medium.com › xebia-engineering › the-recommended-way-of-testing-http-calls-mockwebserver-by-okhttp-e716f87d6122
The Recommended Way Of Testing HTTP Calls — MockWebServer by OkHttp | by Sugandha Sapra | Xebia Engineering Blog | Medium
April 5, 2021 - I was recently working on a Java-based application that involves HTTP calls. I was required to write the test case for the code that includes the API calls. We all are very much familiar with the fact that it’s not a good practice to invoke the actual API for test cases. My senior advised me to use MockWebServer for writing these API test cases.
Maven Repository
mvnrepository.com › artifact › com.squareup.okhttp3 › mockwebserver
Maven Repository: com.squareup.okhttp3 » mockwebserver
August 17, 2026 - Square’s meticulous HTTP client for Java and Kotlin.
Okio
square.github.io › okhttp › 3.x › mockwebserver › okhttp3 › mockwebserver › MockWebServer.html
MockWebServer (MockWebServer 3.14.0 API)
okhttp3.mockwebserver · java.lang.Object · org.junit.rules.ExternalResource · okhttp3.mockwebserver.MockWebServer · All Implemented Interfaces: Closeable, AutoCloseable, org.junit.rules.TestRule · public final class MockWebServer extends org.junit.rules.ExternalResource implements Closeable ·
DZone
dzone.com › software design and architecture › integration › how to mock a web server in your java applications
How to Mock a Web Server in Your Java Applications
October 4, 2021 - Java · @Test void test() throws Exception { mockWebServer(); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create("http://localhost:" + server.port() + "/my/resource")) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); assertEquals("TheGreatAPI.com", response.body()); } Note that when we’re creating the HttpRequest, we have to inform the port where the endpoint is.
Top answer 1 of 10
52
Wire Mock seems to offer a solid set of stubs and mocks for testing external web services.
@Rule
public WireMockRule wireMockRule = new WireMockRule(8089);
@Test
public void exactUrlOnly() {
stubFor(get(urlEqualTo("/some/thing"))
.willReturn(aResponse()
.withHeader("Content-Type", "text/plain")
.withBody("Hello world!")));
assertThat(testClient.get("/some/thing").statusCode(), is(200));
assertThat(testClient.get("/some/thing/else").statusCode(), is(404));
}
It can integrate with spock as well. Example found here.
2 of 10
22
You can write a mock with the JDK's com.sun.net.httpserver.HttpServer class as well (no external dependencies required). See this blog post detailing how.
In summary:
HttpServer httpServer = HttpServer.create(new InetSocketAddress(8000), 0); // or use InetSocketAddress(0) for ephemeral port
httpServer.createContext("/api/endpoint", new HttpHandler() {
public void handle(HttpExchange exchange) throws IOException {
byte[] response = "{\"success\": true}".getBytes();
exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
exchange.getResponseBody().write(response);
exchange.close();
}
});
httpServer.start();
try {
// Do your work...
} finally {
httpServer.stop(0); // or put this in an @After method or the like
}
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.
Industrial Logic
industriallogic.com › blog › integration-testing-with-mockwebserver
Integration Testing with MockWebServer
February 15, 2021 - As many of you know, Spring is deprecating RestTemplate and replacing it with WebClient. Mocking a server with RestTemplate was done with Spring’s MockRestServiceServer, which was able to mock the endpoint your service would normally call. There is a way to almost replicate that functionality using MockWebServer (okhttp).
Stevenschwenke
stevenschwenke.de › testingJavaHttpClientsWithMockWebServer
Testing Java HTTP Clients with MockWebServer
July 18, 2022 - <!-- Mocking Web Servers for Testing --> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>okhttp</artifactId> <version>4.0.1</version> <scope>test</scope> </dependency> <dependency> <groupId>com.squareup.okhttp3</groupId> <artifactId>mockwebserver</artifactId> <version>4.0.1</version> <scope>test</scope> </dependency>
javathinking
javathinking.com › blog › how-to-set-mockwebserver-port-to-webclient-in-junit-test
How to Set MockWebServer Dynamic Port to WebClient in Spring Boot JUnit Tests — javathinking.com
When you start MockWebServer, it automatically binds to a random port. Here’s how to start it and get its base URL (with the dynamic port). In your test class, start the server once per test class (using @BeforeAll) and shut it down after tests (using @AfterAll): // src/test/java/com/example/demo/service/WeatherServiceTest.java import okhttp3.mockwebserver.MockWebServer; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class WeatherServiceTest { // Sta
CodingTechRoom
codingtechroom.com › question › mock-web-server-unit-testing-java
How to Use a Mock Web Server for Unit Testing in Java? - CodingTechRoom
} @After public void tearDown() throws IOException { mockWebServer.shutdown(); } } Mock web servers are essential for reliable unit testing when your application depends on external web services. By using a mock server, you can simulate the responses from these services without making actual ...
Okio
square.github.io › okhttp › 3.x › mockwebserver › index.html
Overview (MockWebServer 3.14.0 API)
JavaScript is disabled on your browser · Frame Alert · This document is designed to be viewed using the frames feature. If you see this message, you are using a non-frame-capable web client. Link to Non-frame version