2013-06-26 32 views
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使用反射來調用私有方法

+0

我希望使方法包成爲私有的,可能作爲包私有助手類的一部分。吻。 – assylias

+2

另外,_why_你需要知道自定義異常是從私有方法拋出的嗎?通常應該嘗試測試被測單元的暴露界面,否則,如果你改變了實現,你的測試將因無正當理由而開始失敗。 – DaveH

+0

@assylias同意但只有當你有權訪問源代碼時纔有可能;我沒有:( –

回答

0

你的設計是典型的,當你需要的時候拋出一個異常做額外的驗證。唯一的評論,我會做的是,你不需要failexception.expect照顧你的。

另外,您不需要也不應該投射到CustomException。這可能會導致ClassCastException,而不是錯誤消息,說明expected CustomException, received SomeOtherException