我有一個例外處理程式,如下所示:
我有一個例外處理程式。
@ControllerAdvice
public class GlobalExceptionHandlerController{
@ExceptionHandler(value = NoHandlerFoundException.class)
public ResponseEntity<CustomErrorResponse> handleGenericNotFoundException(NoHandlerFoundException e,WebRequest req) {
CustomErrorResponse error = new CustomErrorResponse("NOT_FOUND_ERROR", e.getMessage())。
error.setTimestamp(LocalDateTime.now())。
error.setStatus((HttpStatus.NOT_FOUND.value())。
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND)。
}
}
我不知道從哪里下手,我在其他類中有一些測驗,它拋出了NoHandlerException,但是當我檢查junit覆寫率時,handleGenericNotFoundException沒有被高亮顯示。
我對GlobalException的測驗類如下:
@SpringBootTest
@RunWith(SpringRunner.class)
class GlobalExceptionTest{
@InjectMocks
GlobalExceptionHandlerController gxhc。
@Mock
WebRequest req;
@Test(expected=NoHandlerMethodFoundException.class)
public void throwNotFoundException() throws NoHandlerMethodFoundException{
throw new NoHandlerMethodFoundException("POST", "http:localhost",httpHeaders)。
}
uj5u.com熱心網友回復:
不要在你的測驗中拋出例外,而是將其作為引數傳遞給你的例外處理程式,然后驗證結果:
public class GlobalExceptionHandlerControllerTest {
private final GlobalExceptionHandlerController handler = new GlobalExceptionHandlerController() 。
public void handleGenericNotFoundException() {
NoHandlerMethodFoundException e = new NoHandlerMethodFoundException("POST"。"http: localhost", httpHeaders)。)
ResponseEntity<CustomErrorResponse> result = handler.handleGenericNotFoundException(e)。
assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode())。
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/319997.html
標籤:
