fashuser
fashuser

Reputation: 1479

Write 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 to that controller redirects to exception handler if certificate is not valid.

Upvotes: 4

Views: 12318

Answers (3)

effedetto
effedetto

Reputation: 1

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());
}

Upvotes: -1

geoand
geoand

Reputation: 64011

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

Upvotes: 3

Dahai
Dahai

Reputation: 47

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.

Upvotes: -1

Related Questions