Spring Boot,全局异常处理和测试

4
长话短说,我的服务会抛出EntityNotFound异常。默认情况下,Spring Boot不知道这是什么异常以及如何处理它,只会显示“500 Internal Server Error”。
我别无选择,只能实现自己的异常处理机制。
有几种方法可以解决这个问题,我选择使用@ControllerAdvice和@ExceptionHandler方法。
@ControllerAdvice
public class GlobalExceptionHandler {

@ExceptionHandler(EntityNotFoundException.class)
public ResponseEntity<ErrorDetails> handleNotFound(EntityNotFoundException exception, HttpServletRequest webRequest) {
    ErrorDetails errorDetails = new ErrorDetails(
            new Date(),
            HttpStatus.NOT_FOUND,
            exception,
            webRequest.getServletPath());

    return new ResponseEntity<>(errorDetails, HttpStatus.NOT_FOUND);
 }
}

当异常被抛出时,新的处理程序会捕获异常并返回一个包含消息的漂亮的JSON,例如:

{
"timestamp": "2018-06-10T08:10:32.388+0000",
"status": 404,
"error": "Not Found",
"exception": "EntityNotFoundException",
"message": "Unknown employee name: test_name",
"path": "/assignments"
}

实现并不难,最困难的部分是测试。

首先,在测试期间,Spring似乎不知道新处理程序。 我该如何告诉Spring意识到处理此类错误的新实现?

@Test
public void shouldShow404() throws Exception {
    mockMvc.perform(post("/assignments")
            .contentType(APPLICATION_JSON_UTF8_VALUE)
            .content(new ClassPathResource("rest/assign-desk.json").getInputStream().readAllBytes()))
            .andExpect(status().isNotFound());
}

我认为,这个测试应该通过,但它没有通过。
欢迎任何想法。 谢谢!

你是如何初始化测试类的?你使用了哪个运行器? - raiyan
"@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc" 代码 - D2k
2个回答

2
我找到了答案。
致相关人员:
设置类的属性:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class GlobalExceptionHandlerTest{
//
}

和测试:

@Test
public void catchesExceptionWhenEntityNotFoundWithSpecificResponse() throws Exception {

    mockMvc.perform(post("/assignments")
            .contentType(MediaType.APPLICATION_JSON_UTF8)
            .content(new ClassPathResource("rest/assign-desk.json").getInputStream().readAllBytes()))
            .andExpect(status().isNotFound())
            .andExpect(jsonPath("status").value(404))
            .andExpect(jsonPath("exception").value("EntityNotFoundException"))
            .andExpect(jsonPath("message").value("Unknown employee name: abc"));
}

谢谢大家。

1

可能是问题Github问题的重复。不知道你如何设置测试类。但如果你的测试类使用WebMvcTest进行注释,则所有控制器和控制器建议应该被注册。


"@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc" - D2k
你尝试过使用WebMvcTest吗? - raiyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接