如何使用 Mockito 测试 class 中的 throws 子句

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

流程从 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
    }
}


}

这是我的测试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.
  } }
}

当行 Response response = classtotest.method();正在执行然后控制将进入 Test class 的缓存块。我想获取使用 myException ExceptionHandler 创建的 Response 并测试其响应代码。谁能告诉我如何使用 Mockito 做到这一点?

为什么不用这个注解

@Test(expected=MyException.class)

and to assert that the exception has occurred while you're calling your method

//use the mock and call another method that throws an error
when(yourMock.anotherMethod()).thenThrow(new MyException(Constant.ERROR_CODE));

您需要在@Test 中使用expected 字段来通知junit 测试用例这是预期的异常。

  @Test(expected=Expectedexception.class)
public void testMethod(){
  ClassToTest classtotest = new ClassToTest();
  Response response  = classtotest.method(); 
  //your test case
}

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

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