调用MockMvc时,Java Mockito无法正常工作

时间:2017-11-08 14:41:13

标签: java mockito integration-testing mockmvc

对于测试,我使用MockMvc向Controller发出POST请求,我想模拟一个特定的服务调用,以便它什么都不做(使用Mockito.doNothing())。如果我在@Test中调用该方法,那么它完美地工作并且不调用该方法。当我执行mockMvc.perform(..)并且执行命中控制器时,会出现问题,方法doNothing()被忽略并且函数被执行。 我在WebApplicationContext中运行Spring MVC测试。

这是设置:

@Mock
private MyService myService;

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

这部分有效。当调用myFuncToIgnore()时,会跳过它。

@Test
public void myTest() throws Exception {
    Mockito.doNothing().when(myService)
    .myFuncToIgnore(isA(String.class), isA(String.class));

    myService.myFuncToIgnore("", "");
}

这部分不起作用。当mockMvc调用控制器时,执行块。请注意,控制器调用一个接口,该接口的实现调用MyService,这是一个名为MyServiceImpl的impl接口。这是代码:

mockMvc.perform(
            post(serviceContextPath)
                    .contentType(MediaType.APPLICATION_JSON)
                    .header("X-Request-Language", "en"))
            .andDo(print())
            .andExpect(status().isOk())
            .andReturn();

你有什么建议吗?

0 个答案:

没有答案