使用MockMvc和Mockito测试ExceptionHandling

时间:2016-07-10 23:52:21

标签: spring spring-mvc mockito mockmvc spring-mvc-test

我想用 MockMvc Mockito 测试我的 RestController 。我有 providerController 注入服务, providerService 抛出 ProviderNotFoundException ,如果找不到此ID的证明者。此外,我还有 ExceptionHandler 来处理此异常。

@RestController
@RequestMapping
public class ProviderController {

    @Autowired
    private ProviderService providerService;

    @Autowired
    private RestErrorFactory restErrorFactory;

    ...

    @RequestMapping(value = "/{id}")
    public Provider findOne(@PathVariable("id") String id) throws ProviderNotFoundException {
        return providerService.findOne(id);
    }

    @ExceptionHandler(ProviderNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public @ResponseBody RestError providerNotFound(ProviderNotFoundException exception) {
        return restErrorFactory.create(HttpStatus.NOT_FOUND,
            String.format("Provider with id '%s' not found", exception.getRequestedId()));
   }
}

这个控制器的工作很好。但是,当我尝试测试它时,我有这样的代码:

@RunWith(MockitoJUnitRunner.class)
public class ProviderControllerTest {

    @InjectMocks
    private ProviderController providerController;

    @Mock
    private ProviderService providerService;

    private MockMvc mockMvc;

    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        this.mockMvc = MockMvcBuilders.standaloneSetup(providerController)
            .apply(documentationConfiguration(restDocumentation))
            .build();
    }

    ...

    @Test
    public void testFindOneNotFound() throws Exception {
        when(providerService.findOne(anyString()))
            .thenThrow(new ProviderNotFoundException(anyString()));

        this.mockMvc
            .perform(
                    get("/pizza-house")
                        .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isNotFound());

        verify(providerService, times(1)).findOne(anyString());
        verifyNoMoreInteractions(providerService);
    }
}

这次测试失败了,我得到了以下的堆栈跟踪:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.overmind.eattime.provider.service.exception.ProviderNotFoundException

at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at org.overmind.eattime.provider.service.ProviderControllerTest.testFindOneNotFound(ProviderControllerTest.java:106)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.restdocs.JUnitRestDocumentation$1.evaluate(JUnitRestDocumentation.java:55)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:119)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:234)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:74)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Caused by: org.overmind.eattime.provider.service.exception.ProviderNotFoundException
at org.overmind.eattime.provider.service.ProviderController.findOne(ProviderController.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
... 41 more

因此我的 ExceptionHandler 没有从测试中调用。我尝试将 standaloneSetup 替换为 webAppContextSetup 并解决了这个问题,但首先这个测试变成了集成而不是单元,第二个我不能使用Mockito来模拟服务。< / p>

请帮助我使用 standaloneSetup 配置异常处理,或使用 Mockito 模拟我的服务。提前谢谢。

0 个答案:

没有答案