AssertJ を使って、単体テストの結果を検証する方法を書いていきます。
バージョン
動作確認で使用した製品のバージョンは以下の通りです。
目次
- 依存関係の追加
- テストクラスの作成
- テストの実行
- ビルドファイルについて
1. 依存関係の追加
Maven のビルドファイルで、AssertJ のライブラリを追加します。
<dependency> <groupId>org.assertj</groupId> <artifactId>assertj-core</artifactId> <version>3.24.2</version> <scope>test</scope> </dependency>
Gradle の場合は以下の通りです。
testImplementation 'org.assertj:assertj-core:3.24.2'
2. テストクラスの作成
AssertJ で結果を検証するテストケースを作成します。
src/test/java/org/example/CalcTest.java
package org.example; import static org.assertj.core.api.Assertions.assertThat; import org.junit.jupiter.api.Test; class CalcTest { @Test void testAdd() { // 準備 int a = 1; // 実行 int result = a + a; // 検証 assertThat(result).isEqualTo(2); } }
assertThat が AssertJ のメソッドで、検証したい値を引数に指定します。その後の isEqualTo で期待値を指定します。
assertThat(...) の後にピリオドを打つと、IDE が検証メソッドを候補に挙げてくれるので便利です。
3. テストの実行
IDE でテストクラスを実行するか、プロジェクトのルートディレクトリで以下のコマンドを実行します。
mvn test
4. ビルドファイルについて
動作確認で使用したビルドファイルは以下の通りです。
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>test-assertj</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
</properties>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit</groupId>
<artifactId>junit-bom</artifactId>
<version>5.9.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>3.24.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M8</version>
</plugin>
</plugins>
</build>
</project>