JUnit5 の例外のテスト

今更、JUnit4 → 5 の差異のメモです。
未だに JUnit4 を使い続けてるプロジェクトも多いのですが、
JUnit5 の例外のテストは、変わったのを改めてメモ、どこにでも解説があるので、
なんで、今さら。。。とは言え、書き留めます。

JUnit 4 では、、

@Test(expected = Exception.class)
public void testThrowsException() throws Exception {
    // ...
}

JUnit 5 では、、、

@Test
publicvoid testThrowsException() throws Exception {
    Assertions.assertThrows(Exception.class, () -> {
        //...
    });
}

例)NumberFormatException を起こす処理

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.Assertions;
import org.hamcrest.MatcherAssert;
import org.hamcrest.CoreMatchers;
@Test
publicvoid testThrowsException() {
    NumberFormatException ex = Assertions.assertThrows(NumberFormatException.class, ()->{
        // NumberFormatException を起こす処理
    });
    Assertions.assertEquals("For input string: \"A\"", ex.getMessage());
    MatcherAssert.assertThat(ex.getMessage(), CoreMatchers.is("For input string: \"A\""));
}

pom.xml の記述

<dependency>
   <groupId>org.junit.jupiter</groupId>
   <artifactId>junit-jupiter</artifactId>
   <version>5.9.1</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.junit.jupiter</groupId>
   <artifactId>junit-jupiter-engine</artifactId>
   <version>5.9.1</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.assertj</groupId>
   <artifactId>assertj-core</artifactId>
   <version>3.23.1</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.hamcrest</groupId>
   <artifactId>hamcrest-library</artifactId>
   <version>2.2</version>
   <scope>test</scope>
</dependency>

Eclipseなど開発IDEJunit実行ではなく、mvn でテスト実行の為に、、、

<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.22.2</version>
        </plugin>
    </plugins>
</build>