I have mocked a postForObject resttemplate call using mickito.
Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);
But in the actual code, this mocked value is not being used and trying to call the remote location.
String responseString = restTemplate.postForObject(url, input, String.class);
As per my understanding , I have mocked exactly same call. But not working. Any help on this will be thankful.
I'm autowiring the class which contains the testing method in testcase class. And this test class I have created restTemplate using new.
TestClass
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class)
public class ActionImplTest {
@Autowired
private ActionImpl recommendation;
RestTemplate restTemplate = new RestTemplate();
@Test
public void performActionTest() throws Exception {
String textInput = "InputText";
Map<String, Object> map = new HashMap<String, Object>();
map.put("convId", "C123");
map.put("reID", 1);
map.put("chID", "Chann_1");
String convID = "1254356671563";
String chId = "2";
String responseString = "Success"
Mockito.when(restTemplate.postForObject(Mockito.eq("remoteServerlocation"), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString);
Map<String, Object> response = recommendation.performAction(textInput, map, convID, chId);
}
}
Add a verify
step at the end of your test, mockito will give you some hints on what was expected and what actually has been called:
Mockito.verify(restTemplate).postForObject(
Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class));
Here is an example of what I meant in the comment referring to the Spring documentation .
@RunWith(SpringRunner.class)
@SpringBootTest
public class ActionImplTest {
@MockBean
private RestTemplate restTemplate;
@Autowired
private ActionImpl recommendation;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.