【发布时间】:2026-01-21 17:20:05
【问题描述】:
我有一个 REST 网络服务应用程序。我正在使用注释@ExceptionHandler 和@RestControllerAdvice 通过异常处理程序处理异常。我的异常是在服务层中抛出的。现在我正在为服务层编写单元测试。我正在使用 Assert.assertThrows 检查异常。抛出异常,测试通过。但是,抛出异常时不会调用异常处理程序方法。我需要在单元测试期间调用异常处理程序方法。测试类和ExceptionHandler类如下。
@RunWith(SpringRunner.class)
public class ServiceTest {
@InjectMocks
private Service testService = new ServiceImpl();
@Mock
private Repository repository;
@Test
public void testException() {
assertThrows(
Exception.class, ()->{
// Code that throws exception.
});
}
}
@RestControllerAdvice
public class ExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleUnknownException(Exception ex) {
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("Body Here");
}
}
【问题讨论】: