0
另一種方法,我需要斷言CustomException
從私營公用事業方法doSomething
斷言異常來自私有方法拋出的Java
這是我工作迄今已和工作的一個拋出。
在測試類級別定義規則
@Rule public ExpectedException exception = ExpectedException.none();
測試方法的主要部分
exception.expect(CustomException.class);
// prepare call to executePrivateMethod
try {
executePrivateMethod(objInstance, "doSomething",
arg0, arg1);
} catch (InvocationTargetException e) {
Assert.assertTrue("Invalid exception thrown",
(e.getCause() instanceof CustomException));
throw (CustomException) e.getCause();
}
Assert.fail("Invalid response");
我想知道是否有/互生/優雅的方式可用來實現這一目標?
P.S:
1.非常有用post,但我的情況不提
2. executePrivateMethod
使用反射來調用私有方法
我希望使方法包成爲私有的,可能作爲包私有助手類的一部分。吻。 – assylias
另外,_why_你需要知道自定義異常是從私有方法拋出的嗎?通常應該嘗試測試被測單元的暴露界面,否則,如果你改變了實現,你的測試將因無正當理由而開始失敗。 – DaveH
@assylias同意但只有當你有權訪問源代碼時纔有可能;我沒有:( –