Neela
Neela

Reputation: 107

Spring Boot Controller Catch Block call from Junit

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.

Upvotes: 0

Views: 458

Answers (0)

Related Questions