在写unit test时,难免会遇到测试私有方法的时候,下面是用PowerMockito测试私有方法的一种方式。
Method method = PowerMockito.method(类名.class, "方法名", 参数1类型.class, 参数2类型.class, ...)
method.invoke(类实例, 参数1, 参数2, ...)
参数X类型.class举例:Date.class
另外,在测试方法中抛出的自定义异常的message时,由于method.invoke不会抛出我们自定义的异常类型,所以我们得用catch Exception的方式而不是catch customException,并且在获取message上方式上有一点点不同(原来是e.getMessage)
try {
Method method = PowerMockito.method(类名.class, "方法名", 参数1类型.class, 参数2类型.class, ...)
method.invoke(类实例, 参数1, 参数2, ...)
} catch(Exception e) {
String msg = e.getCause().getMessage();
}
另外,贴一个我同事写的关于写unit test的文章: https://blog.csdn.net/u014388161/article/details/100662578
刚看到一个和我几乎重复内容的博客(都可以看看的):https://blog.csdn.net/u012760435/article/details/91387408