0
我無法涵蓋以下功能「postJson」與測試(JUnit的/的Mockito),並不能找到一種方式來嘲笑線response = getTarget(path).request().post(entity, Map.class);
模擬請求/使用後的Mockito
//Constructor
public HttpService() {
this.client = ClientBuilder.newClient();
}
Client client;
public Map<String, ?> postJson(String path, Map<String, ?> data){
Map<String, ?> response = null;
try {
Entity<Map<String, ?>> entity = Entity.entity(data, MediaType.APPLICATION_JSON);
response = getTarget(path).request().post(entity, Map.class);
} catch (Exception e) {
LOG.error(e.toString());
}
return response;
}
public WebTarget getTarget(String path){
return client.target(BASE_URI + path);
}
我目前測試
@Test
public void postJsonTest(){
assertEquals(null,new HttpService().postJson("", new HashMap<String,Integer>()));
//Verifica se a função de comunicação com servidor é chamda
Map<String,String> resposta = new HashMap<String,String>();
HttpService mock = spy(HttpService.class);
assertEquals(mock.postJson("",resposta),null);
Mockito.verify(mock,Mockito.atLeast(1)).postJson("", resposta);
Mockito.verify(mock,Mockito.atLeast(1)).getTarget(Mockito.anyString());
}
我找不到在'request()'之後的測試代碼。任何人都可以給我一個例子/解釋我可以如何使用mockito來覆蓋這個函數?
增加在後,客戶端是在類的屬性 –
客戶端已經在實例化類 –
你的問題的構造是在構造函數中的靜態方法調用。你可能想要第二個構造函數不會調用它。然後,您可以在該構造函數中傳遞一個模擬對象,其中'target'方法被模擬。你會想要一個'WebTarget'的模擬,並且還要模擬任何'請求'返回。 –