我是mockito和junit5的新手。我想測驗一下下面的函式:
public boolean checkFunction(String element) {
CloseableHttpClient client = HttpClients.createDefault()。
String uri = "any url im hitting"/span>。
HttpPost httpPost = new HttpPost(uri);
String json = element;
StringEntity物體。
try {
entity = new StringEntity(json)。
httpPost.setEntity(entity)。
httpPost.setHeader("Accept"/span>, "application/json"/span>)。
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")。
}
誰能幫我解決這個問題? 謝謝!
uj5u.com熱心網友回復:
首先你必須重構你的代碼,以獲得更好的可測驗性:
public class Checker {
private final CloseableHttpClient client;
public Checker(CloseableHttpClient client) {
this.client = client。
}
public boolean checkFunction(String element) {
String uri = "http://example.com"/span>;
HttpPost httpPost = new HttpPost(uri)。
String json = element;
StringEntity物體。
try {
entity = new StringEntity(json)。
httpPost.setEntity(entity)。
httpPost.setHeader("Accept"/span>, "application/json"/span>)。
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;
}
注意,依賴性(即在測驗中必須被模擬的東西)現在是通過建構式注入的。這樣,在對這個類進行單元測驗時,它可以很容易地被一個模擬物件所取代:
class CheckerTest {
private final CloseableHttpClient clientMock = Mockito.mock(CloseableHttpClient.class)。
private final Checker checker = new Checker(clientMock)。
public void testCheckFunction() throws Exception {
when(clientMock.execute(any(HttpPost.class)).thenThrow(new RuntimeException("Oops!") )。
assertFalse(checker.checkFunction("dummy"/span>))。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/313448.html
標籤:
