Java 使用 Mockito 处理异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23213452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Handle Exception with Mockito
提问by Shashika
I'm using Mockito
in my unit testing. I have a method
我Mockito
在我的单元测试中使用。我有一个方法
public Status getResponse(Request requset) throws DataException{
}
DataException
is my own defined one which inherited from Exception class.
DataException
是我自己定义的,它继承自 Exception 类。
In my test case
在我的测试用例中
static{
when(process.getResponse(any(Request.class))).
thenReturn(new Status("Success"));
}
It gives an error, Unhandled Exception:DataException
它给出了一个错误, Unhandled Exception:DataException
Is there any way in Mockito
to handle this issue without adding try/catch ?
有没有办法在Mockito
不添加 try/catch 的情况下处理这个问题?
采纳答案by Taher Khorshidi
add this to your test method:
将此添加到您的测试方法中:
@Test(expected=DataException.class)
or use this :
或使用这个:
then(caughtException()).isInstanceOf(DataException.class);
for a static-block there is no way other than try-catch.
对于静态块,除了 try-catch 之外别无他法。
Another way is to change DataException
to a RuntimeException
.
另一种方法是更改DataException
为RuntimeException
.
回答by Dawood ibn Kareem
Don't use a static
block. Use a method tagged with @Before
instead, and tack throws Exception
onto its declaration.
不要使用static
块。使用标记的方法@Before
,而是和钉throws Exception
在其声明。