Unable to write test case in Junit 5. I got stuck in this test case

Viewed 20

This is my Globalexceptionhandlerclass.java. I am trying to write junit 5 test cases but getting stuck for this can anyone help me on this please ?

        Globalexceptionhandlerclass.java


        import java.util.Date;
        import java.util.HashMap;
        import java.util.Map;
        import org.apache.commons.logging.Log;
        import org.apache.commons.logging.LogFactory;
        import org.springframework.http.ResponseEntity;
        import org.springframework.web.bind.annotation.ControllerAdvice;
        import org.springframework.web.bind.annotation.ExceptionHandler;
        import org.springframework.web.bind.annotation.RestController;
        import org.springframework.web.context.request.WebRequest;
        import 
     org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
        
        public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
            protected final Log loger = 
            LogFactory.getLog(ResponseEntityExceptionHandler.class);
            @ExceptionHandler(Exception.class)
            ResponseEntity<?> handleAllExceptions(Exception ex, WebRequest request ) {
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("date", new Date());
                result.put("message", ex.getMessage());
                result.put("details", request.getDescription(true));
        
                loger.error(ex);
                
                ResponseEntity<?> responseEntity = ResponseEntity.badRequest().
                        header("exception-erro", "error").
                        body(result);
                
                
                return responseEntity;
                
                
            }
        
        }

This is my GlobalExceptionHandlerTest.java. I got stuck on this it is failing. I tried other things but it is not working.Laaast two lines are failing I don't know why. Anyone please help me to corect this cases. It will be very helpful to me.

GlobalExceptionHandlerTest.java

import javax.servlet.http.HttpServletRequest;
@ExtendWith(MockitoExtension.class)
class ExceptionHandlerControllerAdviceTest {

  /**
   * Given a handle invalid exception when controller advice then return a bad request 
exception.
   */
  @Test
  void handleInvalidFormatException() {
    GlobalExceptionHandler controllerAdvice = new GlobalExceptionHandler();
    ResponseEntity<?> response = controllerAdvice.handleAllExceptions(null, null);
    assertEquals(HttpStatus.BAD_REQUEST.value(), response.getStatusCode().value());

  }

}
0 Answers
Related