我試圖運行下面的單元測試 - 採用TestNG
,Mockito
上Java7
的Mockito UnfinishedStubbingException缺少thenReturn或者你正試圖存根最終方法
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.when;
import static org.powermock.api.mockito.PowerMockito.mockStatic;
import static org.powermock.api.mockito.PowerMockito.doReturn;
import junit.framework.Assert;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.annotations.Test;
@PrepareForTest({TestA.class, TestB.class, Result.class, C.class})
public class TestDummy {
@Test
public void testIt() throws Exception {
mockStatic(TestB.class);
Result r = mock(Result.class);
r.res = 2;
TestB tB = mock(TestB.class);
doReturn(tB).when(TestB.class, "get");
when(tB.doSome(any(C.class))).thenReturn(r);
Result rA = TestA.run();
Assert.assertEquals(2, rA.res);
}
}
下面TestDummy是我試圖運行的源代碼上述的單元測試 -
class TestA {
public static Result run() {
TestB tB=TestB.get();
return tB.doSome(new C());
}
}
class Result {
int res;
}
class TestB {
static final TestB INS = new TestB();
public static TestB get() {
return INS;
}
public Result doSome(C c) {
Result r = new Result();
r.res=1;
return r;
}
}
class C {
}
但失敗,下面的錯誤 -
Running TestDummy
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 1.268 sec <<< FAILURE! - in TestDummy
testIt(TestDummy) Time elapsed: 0.527 sec <<< FAILURE!
org.mockito.exceptions.misusing.UnfinishedStubbingException:
Unfinished stubbing detected here:
-> at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
E.g. thenReturn() may be missing.
Examples of correct stubbing:
when(mock.isOk()).thenReturn(true);
when(mock.isOk()).thenThrow(exception);
doThrow(exception).when(mock).someVoidMethod();
Hints:
1. missing thenReturn()
2. you are trying to stub a final method, you naughty developer!
at TestDummy.testIt(TestDummy.java:25)
看起來是一個微不足道的問題,但在這裏停留了一段時間。希望任何輸入來解決這個問題,而不修改源代碼(修改單元測試 - TestDummy應該沒問題)。我看到很多關於類似/相同問題的帖子,但是這些建議在這裏似乎並不奏效。
謝謝你,讓我的一天:) –