Testing Spring MVC @ExceptionHandler method with Spring MVC Test

前端 未结 7 1820
悲&欢浪女
悲&欢浪女 2020-12-04 20:56

I have the following simple controller to catch any unexpected exceptions:

@ControllerAdvice
public class ExceptionController {

    @ExceptionHandler(Throwa         


        
相关标签:
7条回答
  • 2020-12-04 21:49

    Try it;

    @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"));
        }
    }
    
    0 讨论(0)
提交回复
热议问题