怎么用powermockito 去stubbing 无返回值私有方法
时间: 2023-09-23 12:02:38 浏览: 328
1. 首先需要导入PowerMock和Mockito的相关依赖包。
2. 在测试类中使用@PrepareForTest注解,指定需要mock的类。
3. 使用PowerMockito.spy()方法创建被测试类的spy对象。
4. 使用PowerMockito.doNothing()方法stubbing需要stub的无返回值私有方法。
5. 调用被测试类的方法,验证是否执行了stubbed方法。
示例代码:
```
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.powermock.api.mockito.PowerMockito.*;
@RunWith(PowerMockRunner.class)
@PrepareForTest(TestClass.class)
public class TestClassTest {
@Test
public void testPrivateMethod() throws Exception {
TestClass spy = spy(new TestClass());
doNothing().when(spy, "privateMethod");
spy.publicMethod();
verifyPrivate(spy).invoke("privateMethod");
}
}
class TestClass {
public void publicMethod() {
privateMethod();
}
private void privateMethod() {
// do something
}
}
```
在上面的示例代码中,我们使用PowerMockito.doNothing()方法stubbing了TestClass类中的privateMethod()方法,然后调用了TestClass类中的publicMethod()方法,验证是否执行了stubbed方法。
注意:使用PowerMockito.stub()方法去stubbing私有方法时,需要在@PrepareForTest注解中指定mock的类。同时,也需要在方法调用时使用verifyPrivate()方法验证私有方法是否被执行。
阅读全文
相关推荐












