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

3

流程始于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做到这一点吗?

3个回答

2
为什么不使用这个注解?
@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));

这没有意义。当你期望你的被测试代码抛出异常时,你就不应该 模拟 它。 - GhostCat

2
您可以使用expected属性,但如果您需要测试某些特定的消息,可以尝试类似以下的方法:
 @Test
  public void shouldThrowSomeException() {
        String errorMessage = "";
        try {
            Result result = service.method("argument");
        } catch (SomeException e) {
            errorMessage = e.getMessage();
        }
        assertTrue(errorMessage.trim().equals(
                "ExpectedMessage"));
  }

1

您需要在@Test中使用expected字段来告知Junit测试用例所期望的异常。

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

顺便提一下,在这种情况下,你只需要在测试方法中放入 new ClassToTest().method()。当你期望异常时,完全不需要声明classtotest或response。 - GhostCat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接