2013-01-14 24 views
5

這是從官方JMockit教程:JMockit多個異常作爲結果的方法調用

@Test 
    public void doSomethingHandlesSomeCheckedException() throws Exception 
    { 
     new Expectations() { 
     DependencyAbc abc; 

     { 
      abc.stringReturningMethod(); 
      returns("str1", "str2"); 
      result = new SomeCheckedException(); 
     } 
     }; 

     new UnitUnderTest().doSomething(); 
    } 

是否有可能狀態正好相反,是多個結果和一個返回 - 我需要拋出兩種例外,只有然後返回一個很好的價值。這樣的事情是林尋找:

abc.stringReturningMethod(); 
    returns(new SomeCheckedException(), new SomeOtherException(),"third"); 

這不起作用,JMockit不能投那些例外String(這是stringReturningMethod返回類型)

回答

6

寫這樣的:

abc.stringReturningMethod(); 
    result = new SomeCheckedException(); 
    result = new SomeOtherException(); 
    result = "third"; 
+2

它不會將所有三個調用的結果設置爲「第三」嗎? – Queequeg

+0

沒有。它會記錄'stringReturningMethod()'的三個連續結果。 (「結果」可以是要返回的值,要拋出的異常或要執行的「委託」,JMockit會自動將這些賦值重寫爲對其內部方法的調用,這就是它的工作原理。) –

+0

這不起作用。你必須做'result = new SomeCheckedException(); result = new SomeOtherException();返回(「非異常字符串值」);' – searchengine27

1

我不知道有一個快捷方式,這樣做,但你可以隨時記錄,該方法將被調用幾次:

abc.stringReturningMethod(); 
result = new SomeCheckedException(); 

abc.stringReturningMethod(); 
result = new SomeOtherException(); 

abc.stringReturningMethod(); 
result = "third"; 
+0

這將與'NonStrictExpectations'一起使用嗎? – Queequeg

相關問題