您的位置:首页 > 其它

用PowerMock spy mock private方法

2016-01-27 15:57 162 查看
在实际的工作中,经常碰到只需要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");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: