用PowerMock spy mock private方法

时间:2023-03-09 00:40:19
用PowerMock spy mock private方法

在实际的工作中,经常碰到只需要mock一个类的一部分方法,这时候可以用spy来实现。

被测类:

public class EmployeeService {

    public boolean exist(String userName) {
checkPrivateExist(userName);
checkPublicExist(userName);
return true;
} private void checkPrivateExist(String userName) {
throw new UnsupportedOperationException();
} public void checkPublicExist(String userName){
throw new UnsupportedOperationException();
}
}

如果要测试exist方法,需要mock checkPublicExist和checkPrivateExist方法,而不希望mock exist方法

测试类:

@PrepareForTest(EmployeeService.class)
public class EmployeeServiceTestWithPrivateTest extends PowerMockTestCase{ @ObjectFactory
public ITestObjectFactory getObjectFactory() {
return new PowerMockObjectFactory();
} @Test
public void testExist() {
try {
EmployeeService service = PowerMockito.spy(new EmployeeService());
PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");
PowerMockito.doNothing().when(service).checkPublicExist("powermock");;
boolean result = service.exist("powermock");
Assert.assertTrue(result);
Mockito.verify(service).checkPublicExist("powermock");
PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }

在测试类中,真实的调用了exist方法。

需要注意的是对private方法的mock

PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");

以及对exist方法调用过程的验证

Mockito.verify(service).checkPublicExist("powermock");
PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");