栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Mockito单元测试RestTemplate

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Mockito单元测试RestTemplate

您正在测试MyClass类中的逻辑,因此不应模拟它。

RestTemplate
是MyClass内部的依赖项,因此这正是您需要模拟的内容。通常,它在测试中应如下所示:

这只是一个简单的例子。一个好的做法是检查传递给您的模拟的参数是否等于期望的参数。一种方法是

Mockito.eq()
用实际的预期数据代替。另一个是单独验证它,如下所示:

public ResponseEntity<String> postJson(Set<Type> Types){ try {     String oneString = String.join(",", Types);    Map<String, String> requestBody = new HashMap<>();     requestBody.put("type", oneString);     JSonObject jsonObject = new JSonObject(requestBody);     HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);    ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST,  new HttpEntity<>(request, getHttpHeaders()), String.class);     }         }        return Types;

您可以按如下方式编写上述方法的测试

   @Mock   RestTemplate restTemplate;   private Poster poster;   HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), getHttpHeaders());   ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, request, String.class);   Mockito.verify(restTemplate, Mockito.times(1)).exchange(       Mockito.eq(uri),       Mockito.eq(HttpMethod.POST),       Mockito.eq(request),       Mockito.eq(String.class));   Assert.assertEquals(result, poster.postJson(mockData));   HttpHeaders getHttpHeaders() {       HttpHeaders headers = new HttpHeaders();       headers.add(// whatever you need to add);       return headers;   }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609551.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号