【发布时间】:2021-11-06 00:16:28
【问题描述】:
我是 mockito 和 junit5 的新手。我正在尝试测试以下功能:
public boolean checkFunction(String element) {
CloseableHttpClient client = HttpClients.createDefault();
String uri = "any url im hitting";
HttpPost httpPost = new HttpPost(uri);
String json = element;
StringEntity entity;
try {
entity = new StringEntity(json);
httpPost.setEntity(entity);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Authorization", "any token");
CloseableHttpResponse response = client.execute(httpPost);
String responseBody = EntityUtils.toString(response.getEntity());
client.close();
if (responseBody.contains("any string i wanna check"))
return true;
} catch (Exception e) {
return false;
}
return false;
}
我尝试了以下代码,但无法获得整个代码覆盖率。另外我认为这不是正确的方法。
@Test
public void testCheckFunction() throws Exception {
when(mockClass.checkFunction(Mockito.anyString())).thenReturn(false);
assertEquals(false, mockclass.checkFunction("dummy"));
}
谁能帮我解决这个问题? 谢谢!
【问题讨论】:
-
您不是在测试
checkFunction,而是在模拟它,然后测试模拟......相反,您需要实例化真实对象并仅模拟它的依赖项(http 客户端的东西) . -
@slauth 所以你的意思是我应该把我的模拟类和我的原始类一样对待,并在我的测试中实例化我在原始类中使用的对象?你能用演示代码给我看看吗?
标签: java spring-boot spring-mvc junit mockito