I am calling an external API using HttpClient as below,
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("http://localhost:8080/api"))
.POST(BodyPublishers.ofString(requestBody)).header("Authorization",
authorizationHeader)
.header("Content-Type", "application/json").build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
LOGGER.debug(response.body());
I have tried solution from How to mock HttpClient's send method in junit 5?. This actually does not have information on how to return the expected response in stubbing statement.
I am basically looking to stub below statement so that I can test the expected and actual result without invoking the real API,
client.send(request, HttpResponse.BodyHandlers.ofString());
The real API call returns a json in String format, which I will then be mapping to an entity and use it further.
Could someone please put your thoughts on this. Thanks in advance.
The problem with your test is that as the
HttpClientinstance is created inside the method you are testing, you can't mock it. You need to change your code to be something like the code below.You would probably want to extend the test to make some more assertions about the parameters passed to send, and to test your handling of the response (which isn't shown in your question), but I think this answer explains how to mock the client successfully.