首页 > 解决方案 > 如何对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

标签: javaresttemplatejunit5

解决方案


您正在方法中创建一个新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 上找到

Feature.javaFeatureTest.java


推荐阅读