Search code examples
javajunitmockitojunit4bdd

How to test throws clause in the class to be tested using Mockito


The flow starts from the Controller.callMethod(). It calls a method which throws MyException. MyException is handled by an Exception handler written in the Controller:

public class Controller{

public Response callMethod() throws MyException {

   ClassToTest classToTest = new ClassToTest();
   return(classToTest.method());
   }


@ExceptionHandler(MyException.class)
public @ResponseBody
Response myException(HttpServletRequest req,
        HttpServletResponse res, MyException myException) {

    Response response = new Response();
    response.setResponseCode(myException.getErrorCode());       
    return response;
}

}


 public class ClassToTest {
    public Response method() throws MyException {
        Response response = anotherMethod();
        return response;
    }


    public String anotherMethod(){
        if(//something)
          throw new MyException(Constant.ERROR_CODE);    // I need to test this line
    else
        return //some response
    }
}


}

This is my Test class:

public class Test {

@Test
public void testMethod(){
try{
    ClassToTest classtotest = new ClassToTest();
    Response response  = classtotest.method();  //I want to get response after getting MyException (Response created by the myException ExceptionHandler)
    assertEquals("SUCCESS", response.getResponseCode);
  } catch(Exception e){
     //After getting MyException the control comes here & thats the problem. assertEquals never get executed.
  } }
}

When the line Response response = classtotest.method(); is executing then the control is going in the cache block of Test class. I want to get the Response which is created using the myException ExceptionHandler & test its response code. Can anyone tell me how to do it using Mockito?


Solution

  • You can use the expected attribute, but if you need to test for some particular message, try something like this:

     @Test
      public void shouldThrowSomeException() {
            String errorMessage = "";
            try {
                Result result = service.method("argument");
            } catch (SomeException e) {
                errorMessage = e.getMessage();
            }
            assertTrue(errorMessage.trim().equals(
                    "ExpectedMessage"));
      }