【问题标题】:How to write unit test with okhttp using Mockito & Spring Boot如何使用 Mockito 和 Spring Boot 使用 okhttp 编写单元测试
【发布时间】:2021-12-02 22:20:07
【问题描述】:

我正在尝试在我的 Spring Boot 应用程序中将 okhttp 与 Mockito 一起使用,但我总是在行时收到 NullPointerException

httpClient.newCall(request).execute()

我们如何将 Mockito 与 okhttp 一起使用?

@Component
public class HStatus {

    @Autowired
    private OkHttpClient httpClient;

    public int HCheck() throws URISyntaxException, IOException {

        String url = new URIBuilder("Some URL").build().toString();

        Request request = new Request.Builder().url(url).get().build();

        try (Response resp = httpClient.newCall(request).execute()) {

            return resp.code();

        }

    }

在junit中,我正在尝试做-


@RunWith(MockitoJUnitRunner.class)
public class HStatusTest {
    
    @InjectMocks
    private HStatus hStatus;

    @Mock
    private OkHttpClient httpClient;


    @Test
    public void TestHCheck_Should_Return_200_StatusCode() throws URISyntaxException, IOException {

        Response resp = new Response.Builder()
                .request(new Request.Builder().url("SOME URL").build())
                .protocol(Protocol.HTTP_1_1)
                .code(200).message("")
                .build();

        Mockito.when(httpClient.newCall(ArgumentMatchers.any()).execute).thenReturn(resp);

// Getting NullPointer at this call -> httpClient.newCall(ArgumentMatchers.any()).execute

        int statusCode = hStatus.HCheck();
        
        assertEquals(200, statusCode);

    }
}

【问题讨论】:

  • 请更新更多上下文,包括周边代码和测试代码。
  • 另外,okhttp 源代码是可用的。它有自己的测试。为什么要重复它们?也许您应该改用 rest-assured 或 wiremock 来测试实际的服务器?
  • 你应该通过服务器返回一个模拟响应,而不是来自客户端执行github.com/square/okhttp/tree/master/mockwebserver

标签: java spring-boot nullpointerexception mockito okhttp


【解决方案1】:

我猜你正在创建 OkHttpClient 的新实例。

对于创建新实例并不容易用 mockito 模拟它们。你可以使用 mockito @Spy 但我不喜欢那样。

否则你可以使用powermock

 OkHttpClient mockClient = mock(OkHttpClient.class);
 PowerMockito.whenNew(OkHttpClient.class).withNoArguments().thenReturn(mockClient);

另一种方式: 为 new OkHttpClient() 创建一个 getter 类;并模拟它。

getClient(){
    return new OkHttpClient();
}

模拟

when(class.getClient()).thenReturn(mockClient);

【讨论】:

  • 不应嘲笑客户。服务器和响应应该是
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 2019-07-07
  • 2021-11-17
  • 2020-10-13
相关资源
最近更新 更多