I am writing integration test cases using MockMvc to test my REST API.
Within my implementation of the RESTAPI I am internally using RestTemplate(not directly from the controller but from within a util class which the controller calls) to call a 3rd party REST API. The RestTemplate which I use (to make the 3rd party rest API) is not a spring managed bean instead I am instantiating it as RestTemplate restTemplate = new RestTemplate();
I want to mock the restTemplate call(postForEntity).
I am trying the below approach:
My test class-
@ContextConfiguration(locations = {
"classpath:test-applicationContext.xml"
})
@WebAppConfiguration
public class MockMVCTest {
private MockMvc mockMvc;
private RestTemplate restTemplate
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setUp() {
if (!initalized) {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
restTemplate = (RestTemplate)webApplicationContext.getBean("restTemplate");
}
@Test
public void demo() throws Exception {
when(
restTemplate.postForEntity(
eq("thirdpartyuri"),
any(HttpEntity.class),
eq(MyClass.class))).thenReturn(myresponse);
mockMvc.perform(
post("uriExposedbyme")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.content(MY_PAYLOAD)).andExpect(status().isOk());
}
In my application-context I have the following mock defined:
<bean id="restTemplate" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.springframework.web.client.RestTemplate" /> </bean>
But when I execute my test case the RestTemplate is getting mocked but when a call to RestTemplate happens during the execution the actual resttemplate is called instead of my mock resttemplate.
Please suggest on how I can mock RestTemplate for my test case.