2013-05-21 111 views
28

我有以下簡單的控制器,以捕獲任何意外的異常:測試Spring MVC的@ExceptionHandler方法與Spring MVC的測試

@ControllerAdvice 
public class ExceptionController { 

    @ExceptionHandler(Throwable.class) 
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) 
    @ResponseBody 
    public ResponseEntity handleException(Throwable ex) { 
     return ResponseEntityFactory.internalServerErrorResponse("Unexpected error has occurred.", ex); 
    } 
} 

我想寫使用Spring MVC測試框架的集成測試。這是我到目前爲止:

@RunWith(MockitoJUnitRunner.class) 
public class ExceptionControllerTest { 
    private MockMvc mockMvc; 

    @Mock 
    private StatusController statusController; 

    @Before 
    public void setup() { 
     this.mockMvc = MockMvcBuilders.standaloneSetup(new ExceptionController(), statusController).build(); 
    } 

    @Test 
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception { 

     when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception")); 

     mockMvc.perform(get("/api/status")) 
       .andDo(print()) 
       .andExpect(status().isInternalServerError()) 
       .andExpect(jsonPath("$.error").value("Unexpected Exception")); 
    } 
} 

我在Spring MVC基礎結構中註冊ExceptionController和一個模擬StatusController。 在測試方法我設置一個期望拋出從StatusController異常。

拋出異常,但ExceptionController沒有處理它。

我希望能夠測試ExceptionController獲取異常並返回適當的響應。

有關爲什麼這不起作用以及我該如何做這種測試的想法?

謝謝。

+0

我想在測試異常處理程序不分配,不知道爲什麼,但這是爲什麼發生,看看這個答案http:// stackoverflow。 COM /問題/ 11649036 /的ExceptionHandler - 不工作,用彈簧-MVC-3-1單元測試 – engma

+0

關於這方面的消息?我處於同樣的情況。 – Cemo

+0

我沒有找到解決方案。我決定,我會信任@ExceptionHandler作品和因爲該方法本身很簡單,我決定,我可以生活在沒有測試一個註解。您仍然可以使用常規單元測試來測試該方法。 – C0deAttack

回答

0

由於您正在使用獨立安裝測試,因此需要手動提供異常處理程序。

mockMvc= MockMvcBuilders.standaloneSetup(adminCategoryController).setSingleView(view) 
     .setHandlerExceptionResolvers(getSimpleMappingExceptionResolver()).build(); 

我有同樣的問題,幾天就回來,你可以看到我的問題和解決方案由我回答在這裏Spring MVC Controller Exception Test

希望能我的回答幫你出

-1

試試吧;

@RunWith(value = SpringJUnit4ClassRunner.class) 
@WebAppConfiguration 
@ContextConfiguration(classes = { MVCConfig.class, CoreConfig.class, 
     PopulaterConfiguration.class }) 
public class ExceptionControllerTest { 

    private MockMvc mockMvc; 

    @Mock 
    private StatusController statusController; 

    @Autowired 
    private WebApplicationContext wac; 

    @Before 
    public void setup() { 
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build(); 
    } 

    @Test 
    public void checkUnexpectedExceptionsAreCaughtAndStatusCode500IsReturnedInResponse() throws Exception { 

     when(statusController.checkHealth()).thenThrow(new RuntimeException("Unexpected Exception")); 

     mockMvc.perform(get("/api/status")) 
       .andDo(print()) 
       .andExpect(status().isInternalServerError()) 
       .andExpect(jsonPath("$.error").value("Unexpected Exception")); 
    } 
} 
3

此代碼將增加使用異常控制建議的能力。

@Before 
public void setup() { 
    this.mockMvc = standaloneSetup(commandsController) 
     .setHandlerExceptionResolvers(withExceptionControllerAdvice()) 
     .setMessageConverters(new MappingJackson2HttpMessageConverter()).build(); 
} 

private ExceptionHandlerExceptionResolver withExceptionControllerAdvice() { 
    final ExceptionHandlerExceptionResolver exceptionResolver = new ExceptionHandlerExceptionResolver() { 
     @Override 
     protected ServletInvocableHandlerMethod getExceptionHandlerMethod(final HandlerMethod handlerMethod, 
      final Exception exception) { 
      Method method = new ExceptionHandlerMethodResolver(ExceptionController.class).resolveMethod(exception); 
      if (method != null) { 
       return new ServletInvocableHandlerMethod(new ExceptionController(), method); 
      } 
      return super.getExceptionHandlerMethod(handlerMethod, exception); 
     } 
    }; 
    exceptionResolver.afterPropertiesSet(); 
    return exceptionResolver; 
} 
30

我有同樣的問題,對我下面的作品:

@Before 
public void setup() { 
    this.mockMvc = MockMvcBuilders.standaloneSetup(statusController) 
     .setControllerAdvice(new ExceptionController()) 
     .build(); 
} 
+3

由於spring 4.x.x ..... –

0

這是更好的:

((HandlerExceptionResolverComposite) wac.getBean("handlerExceptionResolver")).getExceptionResolvers().get(0) 

而且不要忘記在掃描@ControllerAdvice豆你@Configuration類別:

@ComponentScan(basePackages = {"com.company.exception"}) 

...測試春天4.0.2.RELEASE