繁体   English   中英

如何使用 Mockito & Spring Boot 使用 okhttp 编写单元测试

[英]How to write unit test with okhttp using Mockito & Spring Boot

我试图在我的 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);

    }
}

我猜你正在创建 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM