0

我正在使用 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。

4

2 回答 2

0

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

@Autowired private WebApplicationContext webApplicationContext;

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

@RunWith(SpringJUnit4ClassRunner.class) 

尽管如此,如果您有问题,请自动将其余模板与您的 RestTemplate 实例正确连接,如下所示。

@Autowired
@Qualifier("restTemplate")
private RestTemplate restTemplate;
于 2016-08-04T11:41:33.223 回答
0

util 类实例化它的私有 RestTemplate,就像你说的:RestTemplate restTemplate = new RestTemplate();。

这意味着它将使用它,而不是在测试中嘲笑的那个。您可以在实际代码中将 RestTemplate 设置为 spring 托管 bean,或者在 util 类上有一个 setter 方法,并使用模拟的 rest 模板在测试中调用这个 setter。

于 2016-08-03T12:29:51.430 回答