Reputation: 635
The test code
@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)));
}
and the code under test
public byte[] getDocument(String path) throws IOException {
path = suffixWithExtension(path);
return restTemplate.getForEntity(docServiceHost + DOC_SERVICE_API_VERSION_DEFAULT + DOCUMENT + path, byte[].class).getBody();
}
For some reason, I'm running into an issue where when the getForEntity
function is called in the function under test , it returns null instead of the mocked response.
Upvotes: 1
Views: 450
Reputation: 27068
Try this. This should work.
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));
Some tips. If you are doing this
client = new ServiceClient(restTemplate, host, fileExtension);
you do not need @InjectMocks
. It is redundant. It is a best practice to use Constructor Injections and not use Field Injections and @InjectMocks
.
I hope you are Mocks are initialized. This is done with
MockitoAnnotations.initMocks(this);
This is also done via some Runner classes(If you are using any)
Upvotes: 1