How to test code that performs an HTTP call (to obtain coverage) with okHttp

I have developed an application using Spring Boot and am now using JUnit for writing unit tests. I'm new to Junit, so I know very little of its potential. I use the handy OkHttp (okhttp3) library to make HTTP calls. This is an example of the method that makes a GET call:

HttpUrl.Builder httpBuilder = HttpUrl.parse(MY_URL).newBuilder();
        
httpBuilder.addQueryParameter("myQueryParameter", myQueryParameter);

Request request = new Request.Builder().url(httpBuilder.build())
                              .get()
                              .addHeader("Cookie", "myCookie=myCookieContent")
                              .build();

Response response = client.newCall(request).execute();

String data = response.body().string();

This code makes an HTTP GET call to the MY_URL URL and retrieves the string representing the JSON of the response. It's really simple code in my opinion, but I have no idea how to use JUnit and Mockito to get a code coverage that also analyzes these specific lines of code. What is the best way to do it?

Upvotes: 0

Views: 1068

Answers (1)

marek.kapowicki
marek.kapowicki

Reputation: 732

you should consider to use the MockWebServer: https://github.com/square/okhttp/tree/master/mockwebserver to mock the response from MY_URL

then You can create the junit test to check your flow: check sample https://rieckpil.de/test-spring-webclient-with-mockwebserver-from-okhttp/

Upvotes: 1

Related Questions