java - Spring Boot、全局异常处理和测试

标签 java spring spring-boot testing error-handling

长话短说。我的服务抛出 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
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"));
}

谢谢大家。

关于java - Spring Boot、全局异常处理和测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50782102/

相关文章:

java - spring-boot-starter-web-reactive + spring-boot-starter-actuator 不能一起工作?

java - 在 RESTFul Web 服务中使用 JMS

java - 缓存刷新显示带有@cacheable 注释的错误

java - Android 4.0 -> 4.3(包括在内)- WebView 页面之间的网络存储丢失

java - spring mvc Autowiring sessionFactory 给出 null 对象

java - 通过 REST Web 服务发送字节数组并接收字符串

Java用奇怪的字符创建Redis键和内容

spring-boot - Maven 项目使用多个 GitLab 包注册表

java - 如何根据单元格中输入的文本内容增加jtable中行的高度

Java SWT 列表错误, "null pointer exception"