Home > Back-end >  How to write Spring boot test case for GlobalExceptionHandler ControllerAdvice
How to write Spring boot test case for GlobalExceptionHandler ControllerAdvice

Time:09-18

I have a Exception Handler like below:

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

}

I don't know where to start for this, I have some test in other class which throws NoHandlerException but when i check junit coverage, handleGenericNotFoundException is not hightlighted.

My test class for GlobalException is below:

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

CodePudding user response:

Instead of throwing the exception in your test, pass it as an argument to your exception handler and then verify the result:

public class GlobalExceptionHandlerControllerTest {

    private final GlobalExceptionHandlerController handler = new GlobalExceptionHandlerController();

    @Test
    public void handleGenericNotFoundException() {
        NoHandlerMethodFoundException e = new NoHandlerMethodFoundException("POST", "http:localhost", httpHeaders);
        ResponseEntity<CustomErrorResponse> result = handler.handleGenericNotFoundException(e);
        assertEquals(HttpStatus.NOT_FOUND, result.getStatusCode());
    }
}
  • Related