如何使用 okHttp 测试执行 HTTP 调用(以获得覆盖率)的代码

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

我已经使用 Spring Boot 开发了一个应用程序,现在正在使用 JUnit 编写单元测试。我是 Junit 的新手,所以我对它的潜力知之甚少。我使用方便的 OkHttp (okhttp3) 库进行 HTTP 调用。这是进行 GET 调用的方法示例:

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();

此代码对 MY_URL URL 进行 HTTP GET 调用并检索表示响应的 JSON 的字符串。在我看来,这是非常简单的代码,但我不知道如何使用 JUnit 和 Mockito 来获得同时分析这些特定代码行的代码覆盖率。 最好的方法是什么?

您应该考虑使用 MockWebServer: https://github.com/square/okhttp/tree/master/mockwebserver 模拟来自 MY_URL

的响应

然后您可以创建 junit 测试来检查您的流程:检查示例 https://rieckpil.de/test-spring-webclient-with-mockwebserver-from-okhttp/