spring exceptionalhandler的java测试

iqxoj9l9  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(347)

我有一个带有控制器和服务的springboot项目。还有一个像-

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()

3gtaxfhh

3gtaxfhh1#

不幸的是,mockito中不支持subbing final方法。您可以使用其他模拟框架,如powermock。
在这种情况下,我倾向于消除使用受保护方法进行模拟的需要:

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());
    }
}

相关问题