Write JUnit test for local @ExceptionHandler

2019-05-14 17:21发布

问题:

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.

回答1:

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).



回答2:

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

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



回答3:

I've Solved In this way :

`@Test(expected=MyException.class) public void shouldThrowException() throws IOException, Exception{

     //Mock Response Controller 

when(client.mymethod(any(MyInputClassOfController.class))).thenReturn(mockedResponse);

    when(innerClassInController.myMethodThatInvokeTheException(mock(MyClass.class)))
    .thenThrow(new MyException("message"));


    this.mockMvc.perform(
            post("/root/search/").contentType(MediaType.APPLICATION_JSON_UTF8)
        .content( "null Request to throw the exception")).andExpect(status().isBadRequest());`