我正在尝试使用TestNG
上的Mockito
Java7
运行以下单元测试 - 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应该没问题)。我看到很多关于类似/相同问题的帖子,但这些建议似乎在这里没有用。
答案 0 :(得分:1)
此问题标有junit4
,但提供的代码(非常有用的MCVE,谢谢:)表示您使用的是testng,TestDummy
包含此导入
org.testng.annotations.Test
所以,我不确定你在用什么。
无论如何,你的代码看起来很稳固,我通过一个简单的改变成功运行它;将@RunWith(PowerMockRunner.class)
添加到TestDummy
。
使用以下方法验证了这一点:
答案 1 :(得分:1)
使用Junit,您可以使用@RunWith
但是使用TestNG,您需要在测试用例中指定:
@ObjectFactory public IObjectFactory getObjectFactory() {
return new org.powermock.modules.testng.PowerMockObjectFactory();
}
请记住在您的pom中添加此依赖项:
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-testng</artifactId>
<version>1.7.3</version>
<scope>test</scope>
</dependency>