Write JUnit test for local @ExceptionHandler
10,672
When using standaloneSetup
all you are doing is performing the setup for the specific controller.
If you don't want to configure the whole application context (which you would do with webAppContextSetup
instead of standaloneSetup
), you can manually setup the exception handler by changing your code to:
@Before
public void setup() throws IOException {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(controller).setHandlerExceptionResolvers(new ExceptionHandlerExceptionResolver()).build();
}
@Test
public void test() throws Exception {
mockMvc.perform(get("/verifyCert.controller").contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON)).andExpect(status().isForbidden());
}
This works because ExceptionHandlerExceptionResolver is the class that Spring MVC uses to handle exceptions based on the @ExceptionHandler
annotation
Check out one of my older relevant answers that covers an ever more difficult case (the use of @ControllerAdvice
on a class that contains @ExceptionHandler
).
Author by
fashuser
Updated on June 28, 2022Comments
-
fashuser almost 2 years
I have the following controller:
class Controller { @ResponseStatus(HttpStatus.OK) @RequestMapping(value = "/verifyCert", method = RequestMethod.GET) public void verifyCertificate() throws CertificateExpiredException, CertificateNotYetValidException { certificate.checkValidity(); } @ResponseStatus(HttpStatus.FORBIDDEN) @ExceptionHandler({CertificateExpiredException.class, CertificateNotYetValidException.class}) public void handleCertificateValidityException(Exception e) {} }
My goal is to that controller redirects to exception handler if certificate is not valid.