[英]Mocked restTemplate.postForObject is not being used in execution of test
I have mocked a postForObject resttemplate call using mickito. 我已经使用mickito模拟了一个postForObject resttemplate调用。
Mockito.when(restTemplate.postForObject(Mockito.eq(remoteServerlocation), Mockito.any(Input.class), Mockito.eq(String.class))).thenReturn(responseString); 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); 字符串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. 这个测试类我已经使用new创建了restTemplate。
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: 在测试结束时添加一个verify
步骤,mockito将为您提供一些提示,告诉您预期的内容和实际的内容:
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 . 这是我在引用Spring文档的注释中所指的示例。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ActionImplTest {
@MockBean
private RestTemplate restTemplate;
@Autowired
private ActionImpl recommendation;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.