测试代码
@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
。这是多余的。最佳实践是使用构造函数注入(inject),而不是使用字段注入(inject)和@InjectMocks。
我希望你的Mocks都被初始化了。这是通过
完成的MockitoAnnotations.initMocks(this);
这也是通过一些 Runner 类完成的(如果您正在使用任何类)
关于java - 模拟函数在指定 return 后返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60979899/