【问题标题】:Spring Boot, Global Exception Handling and TestingSpring Boot,全局异常处理和测试
【发布时间】:2018-11-19 18:45:28
【问题描述】:

长话短说。我的服务抛出 EntityNotFound 异常。默认情况下,Spring boot 不知道这是什么类型的异常以及如何处理它,只是显示“500 Internal Server Error”。

我别无选择,只能实现自己的异常处理机制。

使用 Spring Boot 有多种方法可以解决此问题。我选择将@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());
}

在我看来,这个测试应该通过,但它没有。

欢迎提出任何想法。谢谢!

【问题讨论】:

  • 你是如何初始化测试类的?你用的是什么跑步者?
  • "@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc'code"

标签: java spring spring-boot testing error-handling


【解决方案1】:

找到了答案。

它可能关注的对象:

设置类:

@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"));
}

谢谢大家。

【讨论】:

    【解决方案2】:

    questiongithub issue 可能重复。不知道你如何设置你的测试类。但是,如果您的测试类使用 WebMvcTest 注释,则应注册所有控制器和控制器通知。

    【讨论】:

    • "@RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc"
    • 你试过 WebMvcTest 吗?
    猜你喜欢
    • 1970-01-01
    • 2020-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    • 2021-09-18
    • 2020-03-07
    • 2023-03-28
    • 2021-08-19
    相关资源
    最近更新 更多