JUnitのAssert例外 – JUnit 5とJUnit 4

JUnit 5のassertThrowsアサーションを使用することで、期待される例外をテストすることができます。このJUnitアサーションメソッドは、投げられた例外を返すため、例外メッセージもアサートするために使用できます。

JUnitのAssert Exception

以下は、JUnit 5で例外をアサートする方法を示した簡単な例です。

String str = null;
assertThrows(NullPointerException.class, () -> str.length());

JUnit 5 のアサート例外メッセージ

仮に、以下のようなクラスが定義されているとしましょう。

class Foo {
	void foo() throws Exception {
		throw new Exception("Exception Message");
	}
}

例外とそのメッセージをテストする方法を見てみましょう。

Foo foo = new Foo();
Exception exception = assertThrows(Exception.class, () -> foo.foo());
assertEquals("Exception Message", exception.getMessage());

JUnit 4の予期される例外

テストメソッドで発生する予想される例外を定義するために、JUnit 4の@Testアノテーションのexpected属性を使用できます。

@Test(expected = Exception.class)
public void test() throws Exception {
	Foo foo = new Foo();
	foo.foo();
}

JUnit 4のAssert例外メッセージ

例外メッセージをテストする場合、ExpectedExceptionルールを使用する必要があります。以下は、例外および例外メッセージをテストする方法を示した完全な例です。

package com.scdev.junit4;

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

public class JUnit4TestException {

	@Rule
	public ExpectedException thrown = ExpectedException.none();

	@Test
	public void test1() throws Exception {
		Foo foo = new Foo();
		thrown.expect(Exception.class);
		thrown.expectMessage("Exception Message");
		foo.foo();
	}
}

JUnit 5とJUnit 4での予期しない例外のテストについて、簡単にまとめました。以上です。

弊社のGitHubリポジトリプロジェクトから、JUnit 5のさらなる例をチェックすることができます。

コメントを残す 0

Your email address will not be published. Required fields are marked *