[英]Mockito unable to stub overloaded void methods
我正在使用一些拋出異常的庫,並希望在拋出異常時測試我的代碼是否正常運行。 對其中一個重載方法進行存根似乎不起作用。 我收到此錯誤: Stubber無法應用於void。 不存在變量類型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()));
}
}`
你錯放了右括號。 當使用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()
請注意,這與不使用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.