用PowerMock spy mock private方法
2016-01-27 15:57
162 查看
在实际的工作中,经常碰到只需要mock一个类的一部分方法,这时候可以用spy来实现。
被测类:
如果要测试exist方法,需要mock checkPublicExist和checkPrivateExist方法,而不希望mock exist方法
测试类:
在测试类中,真实的调用了exist方法。
需要注意的是对private方法的mock
PowerMockito.doNothing().when(service,"checkPrivateExist","powermock");
以及对exist方法调用过程的验证
Mockito.verify(service).checkPublicExist("powermock");
PowerMockito.verifyPrivate(service).invoke("checkPrivateExist","powermock");
被测类:
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");
相关文章推荐
- .net 调用webservice 总结
- Android Gradle介绍
- Python--迭代器
- Android OpenCv进行图片比对
- Android Audio System之二:AudioFlinger
- 第 6 章 CSS 盒模型
- 在JAVA中, 静态方法和一般方法有什么区别?
- Nginx配置编写时支持逻辑运算与大小写字母转换的方法
- Android Studio项目目录结构介绍
- iOS百度推送的基本使用
- ListView加载网络图片优化(加二级缓存使滑动流畅)
- JQuery手机端预约时间段选择
- hdu1086 You can Solve a Geometry Problem too
- 如何在Ubuntu 14.04中安装最新版Eclipse
- [golang note] 包和导入
- 安卓与IOS移动段浏览器视频与音频的问题与总结
- 孤立账户
- pem文件转p12
- WebApi是轻量级的,WCF是重量级的,可以Api调用WCF,更灵活
- Git的使用— Git基本概念