Van*_*ard 4 java junit unit-testing mockito powermockito
我有一个具有私有方法的类,并在其正文中调用另一个私有方法.所以我想调用第一个私有方法并模拟第二个私有方法.这是一个例子:
public class ClassWithPrivateMethod {
private int count;
public ClassWithPrivateMethod() {
}
private void countDown() {
while (isDecrementable())
count--;
}
private boolean isDecrementable() {
throw new IllegalArgumentException();
// if (count > 0) return true;
// return false;
}
}
Run Code Online (Sandbox Code Playgroud)
和测试类:
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithPrivateMethodTest.class)
public class ClassWithPrivateMethodTest {
private int count;
private ClassWithPrivateMethod classWithPrivateMethod;
@Before
public void setUp() throws Exception {
count = 3;
classWithPrivateMethod = PowerMockito.spy(new ClassWithPrivateMethod());
}
@Test
public void countDown() throws Exception {
Whitebox.setInternalState(classWithPrivateMethod, "count", count);
PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");
Whitebox.invokeMethod(classWithPrivateMethod, "countDown");
int count = Whitebox.getInternalState(classWithPrivateMethod, "count");
assertEquals(1, count);
PowerMockito.verifyPrivate(classWithPrivateMethod, times(3)).invoke("isDecrementable");
}
}
Run Code Online (Sandbox Code Playgroud)
我调用了第一个私有方法,Whitebox.invokeMethod(classWithPrivateMethod, "countDown");然后像这样模拟第二个PowerMockito.doReturn(true, true, false).when(classWithPrivateMethod, "isDecrementable");.正如你看到的isDecrementable方法应该返回true,true,false值调用时,但PowerMockito呼唤真正的方法.
我正在使用这些依赖项:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>1.10.19</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
我的考试有什么问题?
我在这一行发现了错误:
@PrepareForTest(ClassWithPrivateMethodTest.class)
Run Code Online (Sandbox Code Playgroud)
它应该是:
@PrepareForTest(ClassWithPrivateMethod.class)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2048 次 |
| 最近记录: |