2017-04-03 97 views
4

我想測試異常的返回碼。這裏是我的生產代碼:使用JUnit 4測試自定義異常的錯誤代碼

class A { 
    try { 
    something... 
    } 
    catch (Exception e) 
    { 
    throw new MyExceptionClass(INTERNAL_ERROR_CODE, e); 
    } 
} 

而相應的異常:

class MyExceptionClass extends ... { 
    private errorCode; 

    public MyExceptionClass(int errorCode){ 
    this.errorCode = errorCode; 
    } 

    public getErrorCode(){ 
    return this.errorCode; 
    } 
} 

我的單元測試:

public class AUnitTests{ 
    @Rule 
    public ExpectedException thrown= ExpectedException.none(); 

    @Test (expected = MyExceptionClass.class, 
    public void whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode() throws Exception { 
     thrown.expect(MyExceptionClass.class); 
     ??? expected return code INTERNAL_ERROR_CODE ??? 

     something(); 
    } 
} 
+0

的[測試預期的例外JUnit的正確方法]可能的複製( http://stackoverflow.com/questions/42374416/junit-right-way-of-test-expected-exceptions) –

+0

我正在尋找一個很好的方式來做到這一點。 Try/catch是好的,但它意味着更多的代碼行。這是難看的我的觀點... – Guillaume

+0

請檢查我的答案,希望這種方法將幫助你 –

回答

5

簡單:

@Test 
public void whenSerialNumberIsEmpty_shouldThrowSerialNumberInvalid() throws Exception { 
    try{ 
    whenRunningSomething_shouldThrowMyExceptionWithInternalErrorCode();  
    fail("should have thrown"); 
    } 
    catch (MyExceptionClass e){ 
    assertThat(e.getCode(), is(MyExceptionClass.INTERNAL_ERROR_CODE)); 
    } 

這是所有你需要這裏:

你不想
  • 預計特定的例外,因爲你檢查它的一些特性
  • 你知道你進入特定catch塊;當方法拋出任何其他異常,JUnit會報告說,作爲誤差反正
2

您可以檢查它使用 - 這樣你只需在呼叫不會引發

  • 你不需要任何其他的檢查失敗hamcres匹配器只要thrown.expect超載接收Matcher

    thrown.expect(CombinableMatcher.both(
          CoreMatchers.is(CoreMatchers.instanceOf(MyExceptionClass.class))) 
          .and(Matchers.hasProperty("errorCode", CoreMatchers.is(123)))); 
    

    請注意,您將需要hamcrest匹配添加到您的依賴關係。核心匹配包含在JUnit中是不夠的。

    或者,如果你不想使用CombinableMatcher:

    thrown.expect(CoreMatchers.instanceOf(MyExceptionClass.class)); 
    thrown.expect(Matchers.hasProperty("errorCode", CoreMatchers.is(123)); 
    

    而且,你不需要(expected = MyExceptionClass.class)聲明@Test註釋

  • +0

    好!謝謝! – Guillaume