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

标签 java junit mockito junit4 bdd

流程从 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();正在执行然后控件将进入测试类的缓存 block 。我想获取使用 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 测试要测试的类中的 throws 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38267519/

相关文章:

java - 验证传递方法引用

java - 使用 Java 将 DOC 文件转换为 DOCX

java程序打印null而不是String变量

c# - 什么相当于 C# 中的 JUnit?

java - InterceptSendToEndpoint不拦截Route中的http请求,使用Camel和Springboot

unit-testing - 函数参数和对象的 Kotlin 单元测试

android - Mockito 和 TextUtils

java - Log4j2.properties 中的故障转移配置

java - 在 Java 中访问 super() 类的私有(private)变量 - JChart2D

java - 如何在 REST assured 中调用 put 方法