そろそろ使ってみるかということで入門してみました。
JUnit Jupiter
こちらにも書かれてますが、JUnit 5は複数のサブプロジェクトからなり、JUnit 5でテストを書いたり拡張機能を書くためのクラスはJUnit Jupiterというプロジェクトにあります。なので、テストを書く場合は org.junit.jupiter
配下の各種ライブラリーをインポートして使うことになります。
Gradle から使う
最低限以下の記述が必要になります。 (Gradle 4.6以上が必要です)
dependencies { testCompile('org.junit.jupiter:junit-jupiter-api:5.3.2') testRuntime('org.junit.jupiter:junit-jupiter-engine:5.3.2') } test { useJUnitPlatform() }
junit-jupiter-api
は JUnit Jupiter のテストを書くのに必要なクラス、アノテーション群があります。testCompile
で指定します。junit-jupiter-engine
は JUnit Jupiter のテストを実行するためのTestEngine
実装です。testRuntime
で指定します。test
タスク内のコンフィグレーションでuseJUnitPlatform
を指定することで、JUnit 5のプラットフォームを使うように宣言します。
テストを書く、実行する
基本的な書き方はJUnit 4までと同じで、テストしたいメソッドに @Test
のアノテーションを追加します。アサーションは org.junit.jupiter.api.Assertions
クラスにJUnit 3まででお馴染みの assertEquals
などの基本的なアサーションメソッドがあるので、それを使います。JUnit 4時代の assertThat
や、AssertJなどの別のアサーションライブラリを使いたい場合は、別途HamcrestやAssertJをインストールして使うことができます。
package com.example.project; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; class SampleTests { @Test void onePlusOneEqualsTwo() { assertEquals(2, 1 + 1); } }
実行はGradleのテストタスクで実行します。
$ ./gradlew test > Task :test com.example.project.SampleTests > onePlusOneEqualsTwo() PASSED BUILD SUCCESSFUL in 1s 3 actionable tasks: 2 executed, 1 up-to-date
ちょっと高度な使い方集
BeforeとかAfterとか
@Before
@After
は @BeforeEach
@AfterEach
に、 @BeforeClass
@AfterClass
は @BeforeAll
, @AfterAll
に置き換えられました。
package com.example.project; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; class DBTests { @BeforeAll static void initializeDB() { System.out.println("Initializing Database..."); } @AfterAll static void deleteDB() { System.out.println("Deleting Database..."); } @BeforeEach void insertData() { System.out.println("Inserting test data..."); } @AfterEach void clearData() { System.out.println("Clearing test data..."); } @Test void testWithDB() { System.out.println("Testing..."); } }
Parameterized Test
junit-jupiter-params のライブラリをインストールした上で @ParameterizedTest
をテストメソッドに追加します。パラメタのソースは、簡易的には @CsvSource
でCSV文字列で指定できます。もうちょっと高度にやりたい場合は @ArgumentsSource
アノテーションを使うことで独自の引数のProviderを指定することができます。
dependencies { .... testCompile('org.junit.jupiter:junit-jupiter-params:5.3.2') .... }
package com.example.project; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; class ParameterizedTests { @ParameterizedTest(name = "{0} + {1} = {2}") @CsvSource({ "0, 1, 1", "1, 2, 3", "49, 51, 100", "1, 100, 101" }) void testsForPlus(int first, int second, int expected) { assertEquals(expected, first + second, first + " + " + second + " should equal " + expected); } }
JUnit 4のテストを実行する
junit-vintage-engineを testRuntime
でインストールします。これはJUnit 4以前のテストを実行するためのTestEngine
の実装です。
dependencies { ... testCompile "junit:junit:4.12" testRuntime "org.junit.vintage:junit-vintage-engine:5.3.2" ... }
package com.example.project; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import org.junit.Test; public class JUnit4Tests { @Test public void test() { assertThat(1 + 2, is(3)); } }
拡張機能
JUnit 4の @Rule
のような拡張機能は任意の Extension
classを実装することで実現できます。
詳しくは この辺 参照。
package com.example.project; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.BeforeEachCallback; import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.platform.commons.support.AnnotationSupport; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.Optional; class ExtensionTests { @Test @MyExtension("FOO") void extensionTest() { System.out.println("Running a test..."); } @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @ExtendWith(MyExtensionImpl.class) private @interface MyExtension { String value(); } private static class MyExtensionImpl implements BeforeEachCallback { @Override public void beforeEach(ExtensionContext context) { final Optional<MyExtension> annotation = AnnotationSupport.findAnnotation(context.getTestMethod(), MyExtension.class); System.out.println(String.format("Running my extension with %s...", annotation.get().value())); } } }