[英]Mockito unable to stub overloaded void methods
I am using some library that throws an exception and would like to test that my code behaves correctly when the exception is thrown. 我正在使用一些抛出异常的库,并希望在抛出异常时测试我的代码是否正常运行。 Stubbing one of the overloaded methods does not seem to work.
对其中一个重载方法进行存根似乎不起作用。 I am getting this error: Stubber cannot be applied to void.
我收到此错误: Stubber无法应用于void。 No instance types of variable type T exists so that void confirms to T
不存在变量类型T的实例类型,因此void确认为T.
`public class AnotherThing {
private final Something something;
public AnotherThing(Something something) {
this.something = something;
}
public void doSomething (String s) {
something.send(s);
}
}
public class Something {
void send(String s) throws IOException{
}
void send(int i) throws IOException{
}
}
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class OverloadedTest {
@Test(expected = IllegalStateException.class)
public void testDoSomething() throws Exception {
final Something mock = mock(Something.class);
final AnotherThing anotherThing = new AnotherThing(mock);
doThrow(new IllegalStateException("failed")).when(anotherThing.doSomething(anyString()));
}
}`
You've misplaced the close parenthesis. 你错放了右括号。 When using
doVerb().when()
syntax, the call to when
should only contain the object, which gives Mockito a chance to deactivate stubbed expectations and also prevents Java from thinking you're trying to pass a void
value anywhere. 当使用
doVerb().when()
语法时,对when
的调用应该只包含对象,这使得Mockito有机会停用存根期望并且还防止Java认为你试图在任何地方传递void
值。
doThrow(new IllegalStateException("failed"))
.when(anotherThing.doSomething(anyString()));
// ^ BAD: Method call inside doVerb().when()
doThrow(new IllegalStateException("failed"))
.when(anotherThing).doSomething(anyString());
// ^ GOOD: Method call after doVerb().when()
Note that this is different from when
calls when not using doVerb
: 请注意,这与不使用
doVerb
when
调用不同:
// v GOOD: Method call inside when().thenVerb()
when(anotherThing.doSomethingElse(anyString()))
.thenThrow(new IllegalStateException("failed"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.