【发布时间】:2017-08-30 19:07:15
【问题描述】:
我在使用测试 (JUnit/Mockito) 覆盖以下函数“postJson”时遇到问题,并且找不到模拟行 response = getTarget(path).request().post(entity, Map.class);
//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 覆盖这个功能?
【问题讨论】:
-
帖子中添加,client是类中的一个属性
-
客户端已经在类的构造函数中实例化了
-
你的问题是构造函数中的静态方法调用。您可能想要第二个不调用它的构造函数。然后您可以在该构造函数中传递一个模拟,其中
target方法被模拟。您需要模拟WebTarget,还需要模拟request返回的任何内容。 -
如果以后有时间我会写一个完整的答案,如果没有其他人这样做。
-
我编辑了这个问题,我只是不知道如何在该行的请求之后覆盖任何内容。
标签: java unit-testing testing mockito junit4