java – 如何使用Mockito测试要测试的类中的throws子句

该流程从Controller.callMethod()开始.它调用抛出MyException的方法. MyException由Controller中编写的Exception处理程序处理:

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
    }
}


}

这是我的Test类:

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&创建的Response.测试其响应代码.谁能告诉我如何使用Mockito做到这一点?

解决方法:

您可以使用expected属性,但如果您需要测试某些特定消息,请尝试以下操作:

 @Test
  public void shouldThrowSomeException() {
        String errorMessage = "";
        try {
            Result result = service.method("argument");
        } catch (SomeException e) {
            errorMessage = e.getMessage();
        }
        assertTrue(errorMessage.trim().equals(
                "ExpectedMessage"));
  }
上一篇:如何使用构造函数注入来模拟类


下一篇:java – 使用mockito模拟结果集