流程始于Controller.callMethod()。它调用一个方法,该方法抛出MyException异常。Controller中编写的异常处理程序将处理MyException异常:
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
}
}
}
这是我的测试类:
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.
} }
}
当执行代码Response response = classtotest.method()时,程序的控制权转移到了Test类中的缓存块中。我希望使用myException异常处理程序创建的Response并测试其响应代码。有人能告诉我如何使用Mockito做到这一点吗?