java - 如何对restTemplate进行junit测试?
问题描述
我在用 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;
}
}
纯代码:
@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?
解决方案
您正在方法中创建一个新RestTemplate
对象getfeature()
。所以,嘲笑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 上找到
推荐阅读
- c++ - 我们如何为 C++ 无序集定制我们自己的哈希函数以获得特定的顺序?
- node.js - AWS DynamoD Table 的 StreamSpecification 属性有什么用途?
- android - Dagger 在构建期间“无法访问 SomeComponent”
- javascript - POST 方法在客户端和服务器中都返回空对象
- python - 意外类型“QVariant”
- c# - 如何在域驱动设计中对用户实体中的个人资料图片类型的字段进行建模?
- numbers - 查找第一个和最后一个数字
- python - soup.find 有时只返回“none”?
- amazon-web-services - 使用相同的 API ID 销毁并重新部署私有 AWS API Gateway 实例?还是另一种解决方案?
- python - 按钮声明需要帮助