How to add Spring Global RestExceptionHandler in a standalone controller test in MockMVC?

+1 vote
12 views
asked Nov 20 by Hitesh Garg (434 points)  

I have controller advice to handle the global exceptions in a Spring boot application. It looks like -

Controller

  @RestController
  @RequestMapping("/test")
  private static class TestRestController {

    @GetMapping("/get/{name}")
    public void throwException(@PathVariable("name") String name) {
      throw new RuntimeException(name);
    }
  }

GlobalExceptionHandler

@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
@Slf4j
public class RestExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(Exception.class)
  public ResponseEntity<Object> handleAllOtherExceptions(Exception ex, WebRequest request) {
    return new ResponseEntity<>("Custom Error Response", HttpStatus.INTERNAL_SERVER_ERROR);
  }

TestSetup

  private final TestRestController controller = new TestRestController();
  private final MockMvc mockMvc =
          MockMvcBuilders.standaloneSetup(controller)
                  .build();

Now he using a test with this configuration my global ExceptionHandler i.e. the RestExceptionHandler is not being considered.
How can I make sure that the response is as per my custom exception i.e. "Custom Error Response"?

1 Answer

+1 vote
answered Nov 21 by Rahul Singh (644 points)  
selected Nov 21 by Hitesh Garg
 
Best answer

A very small addition is required in the code you have written.

Since you have created a @RestControllerAdvice there is a way to add the advice in the MockMVC standalone setup by using setControllerAdvice method

private final TestRestController controller = new TestRestController();
private final MockMvc mockMvc =
          MockMvcBuilders.standaloneSetup(controller)
                  .setControllerAdvice(new RestExceptionHandler())
                  .build();
...