java 从 Mockito 模拟中抛出异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5679382/
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
Throwing exceptions from Mockito mock
提问by DaveyBob
Something tells me I'm doing something wrong...it shouldn't be this hard.
有些东西告诉我我做错了……这不应该这么难。
I have a class that relies on some inner class. I'm creating that inner through a protected method so that I can override that in a test to provide a mock. I understand that to get a Mockito mock object to throw an exception from a void method, I have to use doThrow.
我有一个依赖于一些内部类的类。我正在通过受保护的方法创建该内部,以便我可以在测试中覆盖它以提供模拟。我知道要让 Mockito 模拟对象从 void 方法抛出异常,我必须使用 doThrow。
But my problem is that the compiler complains that the call to Mockito.doThrow() is throwing RuntimeException...so then I have to add a throws clause to the method setting up the mock. Is that a bug in Mockito itself? doThrow is declaring something that should happen in the future, but not during the setup of the mock.
但我的问题是编译器抱怨对 Mockito.doThrow() 的调用抛出 RuntimeException ......所以我必须在设置模拟的方法中添加一个 throws 子句。这是 Mockito 本身的错误吗?doThrow 正在声明将来应该发生的事情,但不是在模拟设置期间。
My OuterClass looks like...
我的 OuterClass 看起来像...
public class OuterClass {
protected InnerClass inner;
protected void createInner() { inner = new InnerClass(); }
protected doSomething() {
try {
inner.go();
} catch (RuntimeException re) {
throw new MyException("computer has caught fire");
}
}
}
And my test code looks like...
我的测试代码看起来像......
@Test(expected = MyException.class)
public void testSomething() {
OuterClass outer = new TestOuterClass();
outer.doSomething();
}
public static class TestOuterClass extends OuterClass {
@Override
public void createInner() {
InnerClass mock = Mockito.mock(InnerClass.mock);
Mockito.doThrow(new RuntimeException("test")).when(mock).go(); // PROBLEM
inner = mock;
}
}
回答by Lunivore
Please could you check that the compiler really is complaining about a RuntimeException
?
请您检查一下编译器是否真的在抱怨 a RuntimeException
?
The thing about RuntimeException
is that it shouldn't matter at compile time. I suspect the compiler is actually complaining about MyException
- which I presume is a checked exception, noticed by the compiler, which is thrown by the doSomething()
method. You should be able to simply add the throws MyException
to the test method, which will then be caught by the test runner. Since it's expected, the test runner will pass.
问题RuntimeException
是它在编译时应该无关紧要。我怀疑编译器实际上是在抱怨MyException
- 我认为这是一个已检查的异常,由编译器注意到,由doSomething()
方法抛出。您应该能够简单地将 添加throws MyException
到测试方法中,然后测试运行程序会捕获该方法。既然是预期的,那么测试运行器就会通过。