【发布时间】:2018-03-08 14:30:14
【问题描述】:
我正在尝试在 Java7 上使用 TestNG、Mockito 运行以下单元测试 - TestDummy
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);
}
}
以下是我尝试运行上述单元测试的源代码 -
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 应该没问题)。我看到很多关于类似/相同问题的帖子,但是这些建议似乎在这里不起作用。
【问题讨论】:
标签: java unit-testing mockito testng