Unit testing Apache HttpClient with MockWebServer from OkHttp
Hello everyone, here you will learn unit testing Apache HttpClient with MockWebServer from OkHttp. The Source code download link is provided at the end of this tutorial.
- The Apache HttpClient library allows handling HTTP requests. To use this library add a dependency to your Maven or Gradle build file. You find the latest version here: https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient
- MockWebServer makes it possible to facilely test how our apps comport when making HTTP/HTTPS calls. A mock web server is a program that mocks the behaviour of an actual remote server but doesn't make calls over the internet world.
Apache HttpClient, Okhttp mockwebserver, Jackson databinder dependencies
<properties>
<maven.compiler.target>17</maven.compiler.target>
<maven.compiler.source>17</maven.compiler.source>
</properties>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>mockwebserver</artifactId>
<version>4.0.1</version>
<scope>test</scope>
</dependency>
</dependencies>
Post.java
From Java 14 onwards, the record is a special type of class declaration aimed at reducing the boilerplate code.
package com.knf.dev.demo.apachehttpclientokhttpunitestdemo.client;
public record Post
(String userId, String id, String body, String title) {
}
PostClient.java
package com.knf.dev.demo.apachehttpclientokhttpunitestdemo.client;
import java.io.IOException;
import java.util.List;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import com.fasterxml.jackson.databind.ObjectMapper;
public class PostClient {
private final String baseUrl;
CloseableHttpClient httpClient =
HttpClients.createDefault();
public PostClient(String baseUrl) {
this.baseUrl = baseUrl;
}
public List<Post> fetchAllPosts()
throws InterruptedException, IOException {
HttpGet request = new HttpGet(baseUrl + "/posts");
request.addHeader("content-type", "application/json");
CloseableHttpResponse response = httpClient.
execute(request);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(response.getEntity().
getContent(),
objectMapper.getTypeFactory().
constructCollectionType(List.class, Post.class));
}
}
Test [PostClientTest]
package com.knf.dev.demo.apachehttpclientokhttpunitestdemo.client;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
public class PostClientTest {
private MockWebServer mockWebServer;
private PostClient post;
private static String RESPSONE_ALL;
static {
try {
RESPSONE_ALL = new String(
(PostClient.class.getClassLoader().
getResourceAsStream
("posts-all-success.json"))
.readAllBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
@Before
public void init() {
this.mockWebServer = new MockWebServer();
this.post = new PostClient(mockWebServer.url("/").
toString());
}
@Test
public void fetchAllPosts()
throws InterruptedException, IOException {
mockWebServer.enqueue(new MockResponse().
addHeader("Content-Type", "application/json; "
+ "charset=utf-8")
.setBody(RESPSONE_ALL).setResponseCode(200));
List<Post> result = post.fetchAllPosts();
assertEquals(2, result.size());
assertEquals("title 1", result.get(0).title());
assertEquals("1", result.get(0).userId());
}
@After
public void aftertest() {
try {
mockWebServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Test resource - posts-all-success.json
[
{
"userId": 1,
"id": 1,
"title": "title 1",
"body": "body 1"
},
{
"userId": 1,
"id": 2,
"title": "title 2",
"body": "body 2"
}
]
Execute unit test:
Github repository download link is provided at the end of this tutorial
Step 1: Download or clone the source code to a local machine.
Step 2: mvn clean install
mvn install will invoke mvn validate, mvn compile, mvn test, mvn package etc.