gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:06:49 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com