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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 21:22:07  来源:igfitidea点击:

Handle Exception with Mockito

javamockito

提问by Shashika

I'm using Mockitoin my unit testing. I have a method

Mockito在我的单元测试中使用。我有一个方法

public Status getResponse(Request requset) throws DataException{
}

DataExceptionis 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 Mockitoto 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 DataExceptionto a RuntimeException.

另一种方法是更改DataExceptionRuntimeException.

回答by Dawood ibn Kareem

Don't use a staticblock. Use a method tagged with @Beforeinstead, and tack throws Exceptiononto its declaration.

不要使用static块。使用标记的方法@Before,而是和钉throws Exception在其声明。