我有一个 REST Web 服务应用程序。我正在使用注释@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");
}
}