Mockito:替换抛出异常的方法

时间:2017-06-06 08:24:48

标签: java mockito

我有这个界面:

public interface IEnd<T> {
    T get() throws FluentApiException;
}

public interface IFluentEntityCollectionRelation<ID, T> extends IEnd<Iterable<T>>

我正在尝试模拟此接口,以便在调用时返回一个具体的空Iterable<T>对象:

IFluentEntityCollectionRelation<String, Plan> plans = any();
when(plans.get()).thenReturn(new ArrayList<Plan>());

然而,我收到了编译错误:

  

未处理的异常类型FluentApiException

因为IEnd<>.get()会引发FluentApiException异常从未捕获过。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

简单:您只需更改测试代码,如

@Test
public void testWhatever() throws FluentApiException

当然,测试用例不应该抛出异常。如果它被抛出,将导致测试用例失败。

换句话说:你根本就不在乎。通过将此已检查的异常添加到调用get()的测试方法,使编译器更高兴。