java 如何在mock RestTemplate时返回ResponseEntity

avwztpqn  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(169)

下面是我的方法,我正在尝试单元测试

public class Emp {
  public String getName() {
    ResponseEntity<LinkedHashMap> res = restTemplate.postForEntity(url, null, LinkedHashMap.class);
    return res.getBody().get("name");
  }
}

我的单元测试代码如下

LinkedHashMap<String, String> map = new LinkedHashMap<>();
        map.put("name", "foo");
        ResponseEntity<LinkedHashMap> entity = new ResponseEntity<>(map, HttpStatus.OK);

        Mockito.when(restTemplate.postForEntity(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(entity);

但我得到编译错误作为
java:找不到thenReturn(org.springframework.http.ResponseEntity)的合适方法<java.util.LinkedHashMap>
经过多次试验,还是不能消除这个错误。
有人能指出这里的错误以及我如何修复单元测试代码吗?
谢谢

4xy9mtcn

4xy9mtcn1#

经过多次试验,还是不能消除这个错误。有人能指出这里的错误以及我如何修复单元测试代码吗?
出现此编译错误是因为您尝试将thenReturn与泛型类型ResponseEntity<LinkedHashMap>一起使用。Mockito希望您在特定示例中使用thenReturn,而不仅仅是泛型类型。
您可以通过使用ResponseEntity类来修复此错误,该类具有与方法的返回值类型匹配的特定泛型类型:

.
..
...

LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("name", "foo");
ResponseEntity<LinkedHashMap<String, String>> entity = new ResponseEntity<>(map, HttpStatus.OK);

Mockito.when(restTemplate.postForEntity(Mockito.anyString(), Mockito.isNull(), Mockito.eq(LinkedHashMap.class)))
               .thenReturn(entity);

...
..
.

相关问题