使用mockMVC进行集成测试时模拟非弹簧管理对象

时间:2016-08-03 11:37:03

标签: java spring spring-mvc mockmvc springmockito

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

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

2 个答案:

答案 0 :(得分:0)

util类实例化其私有RestTemplate,就像你说的那样:RestTemplate restTemplate = new RestTemplate();.

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

答案 1 :(得分:0)

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

sudo apt-get install software-properties-common
sudo add-apt-repository ppa:ondrej/php5-5.6
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install php5

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

@Autowired private WebApplicationContext webApplicationContext;

如果您遇到问题,请使用您的RestTemplate实例自动连接其余模板,如下所示。

@RunWith(SpringJUnit4ClassRunner.class) 
相关问题