LoginSignup
3
4

More than 5 years have passed since last update.

ExpectedException ルールで期待した例外のスタックトレースを出力する

Last updated at Posted at 2015-03-11

はじめに

JUnit のExpectedException ルールを使用すると例外の発生をテストできます。
(ExpectedExceptionについての記事 : ExpectedException ルールを使いこなしたい)

当記事では、例外を検査すると同時にスタックトレースを標準エラー出力などへ出力する方法について記しています。例外内容を目視でも確認したいようなケースを想定しています。

バージョンは JUnit 4.10以降であれば問題ないと思います。

before

今までは例外を検査すると同時にログを出力したい場合、このような方法でやっていました。

ExpectedExceptionTest.java(before)
public class ExpectedExceptionTest {
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    @Test
    public void testExpectedException() {
        /* Setup */
        thrown.expect(NullPointerException.class);
        /* Exercise */
        try {
            target.execute(); // テスト対象のメソッド
        } catch (NullPointerException e) {
            e.printStackTrace();
            throw e;
        }
    }
    ...
}

ただ、これじゃ Rule 使ってる意味がほぼなくなっちゃいますし、テストメソッドごとにtry-catch書くのもだるいです。

after(解決策)

RuleChainとTestWatcher ルールを使用します。

ExpectedExceptionTest.java(after)
public class ExpectedExceptionTest {
    private ExpectedException thrown = ExpectedException.none();

    private TestWatcher watcher = new TestWatcher() {
        @Override
        protected void failed(Throwable e, Description description) {
            e.printStackTrace();
        }
    };

    @Rule
    public TestRule chain = RuleChain.outerRule(thrown).around(watcher);

    @Test
    public void testExpectedException() {
        /* Setup */
        thrown.expect(NullPointerException.class);
        /* Exercise */
        target.execute(); // テスト対象のメソッド
    }
    ...
}

若干フィールドの記載が増えましたが、各テストメソッドはシンプルに書けるようになりました。

おわり

もし他にいい方法があれば教えてください!

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4