繁体   English   中英

使用MockMVC进行集成测试时模拟非Spring管理的对象

[英]mock a non spring managed object while integration testing using mockMVC

我正在使用MockMvc编写集成测试用例来测试我的REST API。

在我实现RESTAPI的过程中,我在内部使用RestTemplate(不是直接从控制器而是从控制器调用的util类中)调用第三方REST API。 我使用的RestTemplate(用于使第三方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。

util类实例化其私有RestTemplate,如您所说:RestTemplate restTemplate = new RestTemplate();。

这意味着它将使用它,而不是在测试中嘲笑的那个。 您可以在实际代码中使RestTemplate成为spring托管的bean,也可以在util类上使用setter方法,然后使用模拟的rest模板在测试中调用此setter。

根据提供的信息,我可以说尝试进行以下更改并检查是否解决了您的问题。 我看到的是因为您将WebApplicationContext自动连接为

@Autowired private WebApplicationContext webApplicationContext;

开发配置文件可能会被注入,而不是测试配置文件。 因此,您是否可以将此注释放在测试类顶部的测试配置文件中标记该类

@RunWith(SpringJUnit4ClassRunner.class) 

如果仍然有问题,请按如下所示自动将其余模板与RestTemplate实例自动连线。

@Autowired
@Qualifier("restTemplate")
private RestTemplate restTemplate;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM