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'的模拟,并且还要模拟任何'请求'返回。 –