我在使用 Mockito 模拟restTemplate 时遇到问题
要测试的代码:
public class Feature{
public static String getfeature(String url){
RestTemplate restTemplate = new RestTemplate();
String xml = "\"feature\": 1";
String json = restTemplate.postForObject(url, xml, String.class);
return json;
}
}
junit代码:
@Mock
RestTemplate restTemplate=mock(RestTemplate.class);
@Test
public void testGetfeature(){
string testResponse= "\"feature\": 1";
Mockito.when((String)restTemplate.postForObject(
Mockito.any(String.class),
Mockito.any(Map.class),
Mockito.any(Class.class)
)).thenReturn(testResponse);
Feature feature = new Feature();
feature.getfeature("http://mockValue");
}
我在feature.getfeature("http://mockValue ")处设置了断点。它仍然尝试连接到远程服务器。我不希望 postForObject 连接到 http://mockValue 。 我应该如何模拟restTemplate以使postForObject不连接到http://mockValue ?
最佳答案
您正在 getfeature()
方法中创建一个新的 RestTemplate
对象。因此,模拟 RestTemplate
没有效果。要么将 RestTemplate
作为 getfeature()
方法中的参数,要么将其作为 Feature
类中的构造函数参数。
然后从测试类中,您可以模拟 RestTemplate 并传递它,如下所示:
Feature feature= new Feature(mockRestTemplate);
feature.getfeature(url);
或者
Feature feature = new Feature();
feature.getfeature(mockRestTemplate, url);
您必须根据决定对要素类进行必要的更改。
这是运行代码示例:
主类:
public class Feature {
public static String getFeature(String url, RestTemplate restTemplate) {
return restTemplate.postForObject(url, "", String.class);
}
}
测试类:
请注意 RestTemplate
被模拟的方式,然后模拟响应。
public class FeatureTest {
@Test
public void testFeature() {
RestTemplate restTemplate = Mockito.mock(RestTemplate.class);
Mockito.when(restTemplate.postForObject(Mockito.any(String.class),
Mockito.any(Object.class), Mockito.any(Class.class))).thenReturn("abc");
System.out.println(Feature.getFeature("http://abc", restTemplate));
}
}
运行代码示例也可在 github 处获取。
关于java - 如何对restTemplate进行junit测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57297136/