2017-04-03 11 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の正しい方法]の可能性のある重複したため(expected = MyExceptionClass.class)宣言は必要ありません。 http://stackoverflow.com/questions/42374416/junit-right-way-of-test-expected-exceptions) –

+0

私はそれを行う良い方法を探しています。試してみてください/キャッチはOKですが、より多くのコード行を意味します。それは私の視点で読むことは醜いです... – 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はあなたの依存関係にhamcrestマッチャーを追加する必要がありますMatcher

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

注意を受信する限りthrown.expectが過負荷であるとしてマッチャー。 JUnitに含まれるコアマッチングは十分ではありません。

それともCombinableMatcherを使用しない場合:

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

また、あなたは(@Test注釈

+0

ニース!ありがとうございました! – Guillaume

関連する問題