Java 用Mockito处理异常

Java 用Mockito处理异常,java,mockito,Java,Mockito,我在单元测试中使用了Mockito。我有办法 public Status getResponse(Request requset) throws DataException{ } DataException是我自己定义的一个,它继承自Exception类 在我的测试用例中 static{ when(process.getResponse(any(Request.class))). thenReturn(new Status("Success")); } 它给出

我在单元测试中使用了
Mockito
。我有办法

public Status getResponse(Request requset) throws DataException{
}
DataException
是我自己定义的一个,它继承自Exception类

在我的测试用例中

static{
when(process.getResponse(any(Request.class))).
                thenReturn(new Status("Success"));
}
它给出一个错误,
未处理的异常:DataException


Mockito
中是否有任何方法可以在不添加try/catch的情况下处理此问题?

将此添加到您的测试方法中:

@Test(expected=DataException.class)
或者使用以下命令:

then(caughtException()).isInstanceOf(DataException.class);
对于静态块,除了try-catch之外没有其他方法


另一种方法是将
DataException
更改为
RuntimeException

不要使用
静态块。改为使用在
之前标记有
@的方法,并将
抛出异常
到其声明中。

为什么不能使用try/catch?我想你最近指定了异常来处理它。但是问题在静态块中仍然是一样的。这没有解决问题。这修复了我类似的问题。不知道为什么上面的答案被标记为正确-它没有解决它。