2017-03-26 14 views
0

Eclipse(Ubuntu)でJUnit(4)を使用していくつかのテストを実行しようとしたときに問題が発生しました。エラーがスローされなかった場合に通知する関数testEmptyTitle()を持つ単純なテストクラスを持っています。JUnitがExpectedExceptionメッセージを表示しない

package tests; 

import workshop.WorkshopPaper; 

import static org.junit.Assert.*; 

import org.junit.Ignore; 
import org.junit.Rule; 
import org.junit.Test; 
import org.junit.rules.ExpectedException; 

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

    @Test(expected=IndexOutOfBoundsException.class) 
    public void testEmptyTitle() { 
     thrown.expect(IndexOutOfBoundsException.class); 
     thrown.reportMissingExceptionWithMessage("No exception thrown"); 
    } 
} 

テストを実行しようとすると、"No exception thrown"メッセージが表示されません。 これは私のJUnitのインタフェースがテストを実行した後、次のようになります。

enter image description here

は、この問題を解決する方法はありますか?予想される例外ルールを使用して、あなたはまた、例外をスローするために、任意のクラスのインスタンスを呼び出していない、あるいは単にthrow new IndexOutOfBoundsExceptions();

+0

実際にテストのどこかで例外をスローする必要があるかもしれないと思います。 –

答えて

1

ExpectedExceptionを行うときは、@Test(expected=Class<T>)を必要としない

1

がいるかどうかを確認するのに便利ですが例外のインスタンスは、テストメソッドによってスローされ、あなたのコードで、あなたは下のここを見て、IndexOutOfBoundsExceptionをスローしませんでした:@Test(expected=SomeException.class)やメソッドの例外動作をテストするために使用ExpectedException.expect(SomeException.class)ではなく、どちらか、

一般に
@Test//remove expected exception here, it not required 
public void testEmptyTitle() throws IndexOutOfBoundsException { 
    thrown.expect(IndexOutOfBoundsException.class); 
    thrown.reportMissingExceptionWithMessage("No exception thrown"); 
    throw new IndexOutOfBoundsException();//throw exception here 
} 

両方とも彼女。

ExpectedExceptionクラスのAPIについてはhere、使用方法については簡単な例があります。

+0

ありがとうございます、期待クラスの設定が問題を引き起こしていたことが判明しました。答えの2番目の部分に関しては、例外がスローされた場合に成功すると思われるテストで例外をスローしません。 – August

関連する問題