Spring ExceptionalHandler 的 Java 测试

标签 java spring-boot exceptionhandler controller-advice

我有一个带有 Controller 和服务的 springboot 项目。还有像 GlobalExceptionHandler 这样的 -

public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
 @ExceptionHandler(DataIntegrityViolationException.class)
  public ResponseEntity<Object> handle(DataIntegrityViolationException e, WebRequest request) {
    ....

     String requestPath = ((ServletWebRequest)request).getRequest().getRequestURI();

    // I am using this requestPath in my output from springboot
   ...

  }
}

有人可以告诉我如何在我的单元测试类中编写模拟吗 ((ServletWebRequest)request).getRequest().getRequestURI()

最佳答案

不幸的是,Mockito 中不支持 subbing final方法。您可以使用其他模拟框架,例如 PowerMock。

在这种情况下,我更喜欢消除使用 protected 方法进行模拟的需要:

public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(DataIntegrityViolationException.class)
    public ResponseEntity<Object> handle(final DataIntegrityViolationException e, final WebRequest request) {

        final String requestPath = getRequestUri(request);

        return ResponseEntity.ok().body(requestPath);
    }

    protected String getRequestUri(final WebRequest request) {
        return ((ServletWebRequest) request).getRequest().getRequestURI();
    }
}

测试中的匿名类:

public class GlobalExceptionHandlerTests {

    private final GlobalExceptionHandler handler = new GlobalExceptionHandler() {
        @Override
        protected String getRequestUri(final org.springframework.web.context.request.WebRequest request) {
            return "http://localhost.me";
        };
    };

    @Test
    void test() throws Exception {

        final ResponseEntity<Object> handled = handler.handle(new DataIntegrityViolationException(""),
                null);
        assertEquals("http://localhost.me", handled.getBody());
    }
}

关于Spring ExceptionalHandler 的 Java 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60212266/

相关文章:

visual-studio-2017 - "View Details "缺少表单异常处理程序 VS 2017

java - PAAS 能否解决 BlazeDS 的可扩展性问题?

reactjs - Keycloak - 保护 Spring Boot 应用程序

java - 如何在服务类中添加@valid时处理自定义注释

java - 无法绑定(bind)属性

spring-boot - CSS 中的服务器上下文路径和图像 url

spring - Spring ExceptionHandler 如何处理运行时异常

java - 在 SQLite 中检索 TimeInMillis

java - 在 Java 中,假设我们有一个名为 Foo 的类,obj.getClass().getName() 和 Foo.class.getName() 如何获取相同的结果?

java - Gradle项目是否可以重建其依赖项,跟踪其源更改等?