java - 模拟函数在指定返回后返回 null
问题描述
测试代码
@Mock
private RestTemplate restTemplate;
@InjectMocks
private ServiceClient client;
@Test
public void getDocument() throws IOException {
String fileExtension = "fileextension";
String host = "docserverurl";
String path = "path";
String content = "content";
client = new ServiceClient(restTemplate, host, fileExtension);
when(restTemplate.getForEntity(any(), any()))
.thenReturn(new ResponseEntity(content, HttpStatus.OK));
assertEquals(content, new String(client.getDocument(path)));
}
和被测代码
public byte[] getDocument(String path) throws IOException {
path = suffixWithExtension(path);
return restTemplate.getForEntity(docServiceHost + DOC_SERVICE_API_VERSION_DEFAULT + DOCUMENT + path, byte[].class).getBody();
}
出于某种原因,我遇到了一个问题,当getForEntity
在被测函数中调用该函数时,它返回 null 而不是模拟响应。
解决方案
试试这个。这应该有效。
byte[] content = "content".getBytes();
when(restTemplate.getForEntity(anyString(), any()))
.thenReturn(new ResponseEntity(content, HttpStatus.OK));
final byte[] sds = someClass.getDocument("sd");
assertEquals(new String(content), new String(sds));
一些技巧。如果你正在这样做
client = new ServiceClient(restTemplate, host, fileExtension);
你不需要@InjectMocks
。这是多余的。使用构造函数注入而不使用字段注入和@InjectMocks
.
我希望你是 Mocks 已初始化。这是用
MockitoAnnotations.initMocks(this);
这也可以通过一些 Runner 类完成(如果您正在使用任何类)
推荐阅读
- python - 填写dict的更好方法?
- r - 有没有一种简单的方法可以在 R 中反转数据框中的日期?
- javascript - 为什么 '1' + '2' - 3 给出 9?
- scala - Cats Scala中的序列和遍历以映射类型
- visual-studio - Visual Studio 19 没有将正确的输入传递给 powershell 脚本
- bind - svelte:如何显示列表中每个元素的道具 ID
- instagram-graph-api - Instagram Graph API 最近搜索结果返回空白数据
- c# - 水晶报表查看器未出现在工具箱 Visual Studio 2015 中
- node.js - 如何将 kubernetes 配置中的值提取到 Web 应用程序中
- c# - 为什么 Task.WhenAll 需要在异步方法不需要手动创建的任务时启动?