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.

Technologies Used:

  • Java 17
  • Apache HttpClient
  • OkHttp MockWebServer
  • Maven 3+
  • Jackson databinder

Final project directory:


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.


Comments

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

ReactJS - Bootstrap - Buttons

Spring Core | BeanFactoryPostProcessor | Example

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Custom Exception Handling in Quarkus REST API

ReactJS, Spring Boot JWT Authentication Example

Java, Spring Boot Mini Project - Library Management System - Download

Top 5 Java ORM tools - 2024

Java - DES Encryption and Decryption example