I'm working on spring boot application that makes three external api calls from service layer, so while writing the integration tests, I'm trying to override actual RestTemplate
bean with mocked RestTemplate
bean and when making the three external API calls I specified to return some data
given(this.restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.isA(new ParameterizedTypeReference<TestData1>() {
}.getClass()))).willReturn(ResponseEntity.accepted().body(new TestData1()));
given(this.restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.isA(new ParameterizedTypeReference<TestData2>() {
}.getClass()))).willReturn(ResponseEntity.accepted().body(new TestData2()));
given(this.restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.isA(new ParameterizedTypeReference<List<TestData3>>() {
}.getClass()))).willReturn(ResponseEntity.accepted().body(Arrays.asList(new TestData3())));
But the problem is when ever restTemplate.exchange
method is called it is returning null
as response instead of ResponseEntity
with corresponding body
TestConfig class
@TestConfiguration
@ActiveProfiles("test")
@Profile("test")
public class TestConfig {
@Bean
public RestTemplate restTemplae() {
return Mockito.mock(RestTemplate.class);
}
TestClass
@SpringBootTest(classes = { TestConfig.class })
@ActiveProfiles("test")
@Profile("test")
@RunWith(SpringJUnit4ClassRunner.class)
public class TestClass {
@Autowired
private RestTemplate restTemplate;
@Test
public void taskTest() {
//code
given(this.restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.isA(new ParameterizedTypeReference<TestData1>() {
}.getClass()))).willReturn(ResponseEntity.accepted().body(new TestData1()));
given(this.restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.isA(new ParameterizedTypeReference<TestData2>() {
}.getClass()))).willReturn(ResponseEntity.accepted().body(new TestData2()));
given(this.restTemplate.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.isA(new ParameterizedTypeReference<List<TestData3>>() {
}.getClass()))).willReturn(ResponseEntity.accepted().body(Arrays.asList(new TestData3())));
//code
}