相关疑难解决方法(0)

抛出与Mockito模拟的例外情况

我正在尝试让我的一个模拟对象在调用特定方法时抛出一个已检查的Exception.我正在尝试以下方法.

@Test(expectedExceptions = SomeException.class)
public void throwCheckedException() {
    List<String> list = mock(List.class);
    when(list.get(0)).thenThrow(new SomeException());
    String test = list.get(0);
}

public class SomeException extends Exception {
}
Run Code Online (Sandbox Code Playgroud)

但是,这会产生以下错误.

org.testng.TestException: 
Expected exception com.testing.MockitoCheckedExceptions$SomeException but got org.mockito.exceptions.base.MockitoException: 
Checked exception is invalid for this method!
Invalid: com.testing.MockitoCheckedExceptions$SomeException
Run Code Online (Sandbox Code Playgroud)

看看Mockito文档,他们只使用RuntimeException,是否不可能使用Mockito从模拟对象中抛出已检查的异常?

java mocking mockito

140
推荐指数
5
解决办法
14万
查看次数

尝试使用Mockito引发抛出检查异常的问题

我有下面的界面

public interface Interface1 {
    Object Execute(String commandToExecute) throws Exception;
}
Run Code Online (Sandbox Code Playgroud)

然后,我尝试进行模拟,以便可以测试将其调用的类的行为:

Interface1 interfaceMocked = mock(Interface1.class);
when(interfaceMocked.Execute(anyString())).thenThrow(new Exception());
Interface2 objectToTest = new ClassOfInterface2(interfaceMocked);
retrievePrintersMetaData.Retrieve();
Run Code Online (Sandbox Code Playgroud)

但是编译器告诉我,有一个未处理的异常。Retrieve方法的定义是:

public List<SomeClass> Retrieve() {
    try {
        interface1Object.Execute("");
    }
    catch (Exception exception) {
        return new ArrayList<SomeClass>();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mockito文档仅显示RuntimeException的使用,而我在StackOverflow上也没有看到类似的东西。我正在使用Java 1.7u25和Mockito 1.9.5

java mockito

4
推荐指数
1
解决办法
6931
查看次数

标签 统计

java ×2

mockito ×2

mocking ×1