Write a JUnit test for local @ExceptionHandler

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 for the controller to redirect the exception handler if the certificate is invalid.

+3


source to share


2 answers


When used standaloneSetup

, everything you do is doing customization for a specific controller.

If you don't want to customize the entire application context (which you would do with webAppContextSetup

instead standaloneSetup

), you can manually customize your 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 annotation based exceptions@ExceptionHandler

Please note one of my old relevant answers that covers an increasingly complex case (use @ControllerAdvice

for a containing class @ExceptionHandler

).

+2


source


The property in your class net.scansafe.scancentre21.springmvc.web.easyid.ManageSamlAuthenticationRealmController.verifySecondarySamlSpCertificate(ManageSamlAuthenticationRealmController.java)

is null.



You can debug the class method to find it. You need to add @Autowired for this injection property.

0


source







All Articles