0

I have a controller class with a POST method with @RestController annotation

@RequestMapping(value="/test", method = RequestMethod.POST, produces ="application/json")
   public Response updateDetails(@RequestBOdy Request request) throws ServiceException{
     try{
       //Service call for db connection
       response = service.updateDetails(request);
    }catch(IOException s){s.printStackTrace();}
     catch(InterruptedException e){e.printStackTrace();}
     return response;
   }

The Junit test class is,

@Test
public void test() {
   Request request = new Request();
   request.setId("session");
   Response response = new Response();
   respoonse.setStatus("200");
   response.setMessage("");

 try{
   Service service = Mockito.mock(Service.class);

//mock values to call catch block
   **when(service.updateDetails(any())).thenThrow(new IOException());
   when(controller.updateDetails(any()).thenThrow(new ServiceException());**
   
   RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/test").accept(MediaType.APPLICATION_JSON).content(request).contentType(MediaType.APPLICATION_JSON);

  try{
    MvcResult result = mvc.perform(requestBuilder).andReturn();
    assertNotNull(result);
  }catch(Exception e){e.printStackTrace();}
  catch(IOException e){e.printStackTrace();}
  catch(InterruptedException e){e.printStackTrace();}
 
 }
}

With the above controller and test case, I am trying to cover the catch block but the call is not at all reaching the catch block. I have added @MockBean for the controller class in the test case.

I have done some database update statements only for the service class. So I didn't include that part for that only I have mocked the values.

Kindly help me to do the code coverage for the block in the controller class.

2
  • stackoverflow.com/a/33274821/7155432 check this Commented Oct 6, 2020 at 19:33
  • Thank you so much @VaibS Will try this and let you know Commented Oct 7, 2020 at 16:28

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.