3

I am trying to write test for my controller with the code below. I want to cover the test for the code in the catch block statement but I'm not able to write one. I want to return a Server Response with failure code and message in the catch block.

@PostMapping(COUNTERS)
public ResponseEntity<?> getCounters(@Valid @RequestBody ApartmentCounterListRequest requestData) {
    try {
        log.debug("Entering API for counter list");
        ApartmentCounterListResponse apartmentCounterListResponse = counterService.getAllCounters();
        return ResponseEntity.ok(apartmentCounterListResponse);
    } catch (Exception exception) {
        log.error("Exception in counter list :: ", exception);
        ServerResponse serverResponse = ResponseBuilder.buildVendorFailureMessage(new ServerResponse(),
                RequestResponseCode.EXCEPTION);
        return ResponseEntity.ok(JsonResponseBuilder.enquiryResponse(serverResponse));
    }
}

My test code is as follows:

@Test
@DisplayName("Should return ServerResponse with failure data.")
void Should_Return_Server_Response_On_Exception() throws Exception {

    /*given*/
    ApartmentCounterListRequest apartmentCounterListRequest = ApartmentTestUtil.getApartmentCounterListRequest.
            apply("test", "test");
    Mockito.when(counterServic.getAllCounters()).thenThrow(new Exception());
//        ServerResponse serverResponse = ApartmentTestUtil.getServerExceptionServerResponse.get();

    /*then*/
    mockMvc.perform(
            post(COUNTER_URL)
                    .contentType(APPLICATION_JSON)
                    .content(objectMapper.writeValueAsString(apartmentCounterListRequest)))
            .andExpect(status().isOk())
            .andExpect(MockMvcResultMatchers.jsonPath("$.resultCode", Matchers.is("-6")));
    verify(counterService, times(1)).getAllCounters();
}

When I run this test I am getting the following error:

org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: java.lang.Exception

I have gone through some of the following posts but haven't found a suitable answer yet.

Unit testing code in catch block of a Spring Controller

Java - How to Test Catch Block?

Unit testing code in catch block of a Spring Controller

JUnit for both try and catch block coverage

Can anyone help me write test that covers the catch block or tell me the way to do it?

I have this try catch in my controller to handle any unexpected exceptions. And for different api's I have to send a response with different response code and messages which doesnot allow me to use Exception handler.

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
Sabu Shakya
  • 334
  • 4
  • 15

2 Answers2

6

The method you are mocking does not declare a checked exception, therefore Mockito is not able to throw one from there. Try to have the mock throw an unchecked exception (i.e. RuntimeException).

EricSchaefer
  • 25,272
  • 21
  • 67
  • 103
0

You can try to use willAnswer

 Mockito.when(counterServic.getAllCounters()).thenAnswer(x -> {throw new Exception() });

Maybe this is a bit misused as Answer is used for more complex for when return