I was trying to write a simple test for an API client that uses Spring RestTemplate for the HTTP call. The endpoint gives a byte[]
back.
I want only to test the behaviour of my API client so I mocked this out by trying to return a known byte[] so that I can test that my API client behaves correctly.
When mocking <T> T getForObject(URI url, Class<T> responseType)
of RestTemplate I can't get mockito to match the call with the any()
matcher. The mock returns null
instead.
I want to know:
- if there is way to make mockito match the call
- you have a good idea on how to make this work with another approach
Thanks for your input!
Below some minimal example code for the issue.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import org.junit.jupiter.api.Test;
import org.springframework.web.client.RestTemplate;
class ByteArrayTest {
@Test
void test() {
byte[] expectedBytes = "expected byte array".getBytes();
RestTemplate restTemplate = mock(RestTemplate.class);
when(restTemplate.getForObject(any(), any())).thenReturn(expectedBytes);
byte[] actualBytes = restTemplate.getForObject("http://localhost", byte[].class);
assertEquals(expectedBytes, actualBytes);
}
}