在寫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