我正在使用 MockMvc 编写集成测试用例来测试我的 REST API。
在我的 RESTAPI 实现中,我在内部使用 RestTemplate(不是直接来自控制器,而是来自控制器调用的 util 类)来调用第 3 方 REST API。我使用的 RestTemplate(用于制作第 3 方 Rest API)不是 Spring 托管 bean,而是将其实例化为 RestTemplate restTemplate = new RestTemplate();
我想模拟 restTemplate 调用(postForEntity)。
我正在尝试以下方法:
我的测试课-
@ContextConfiguration(locations = {
"classpath:test-applicationContext.xml"
})
@WebAppConfiguration
公共类 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());
}
在我的应用程序上下文中,我定义了以下模拟:
<bean id="restTemplate" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="org.springframework.web.client.RestTemplate" /> </bean>
但是当我执行我的测试用例时,RestTemplate 被模拟了,但是当在执行期间调用 RestTemplate 时,实际的 resttemplate 被调用,而不是我的模拟 resttemplate。
请建议我如何为我的测试用例模拟 RestTemplate。