【发布时间】:2016-07-08 13:07:01
【问题描述】:
流程从 Controller.callMethod() 开始。它调用一个抛出 MyException 的方法。 MyException 由 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
}
}
}
这是我的测试课:
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 ExceptionHandler 创建的响应并测试其响应代码。谁能告诉我如何使用 Mockito 做到这一点?
【问题讨论】:
标签: java junit mockito junit4 bdd