S-JIS[2017-09-15] 変更履歴
JUnit5のParameterizedTestについて。
|
JUnit5(Jupiter)では、テストメソッドの引数にテストで使う値を(複数)指定して同じテストを実行することが出来る。
これには@ParameterizedTestアノテーションを使うが、バージョン5.0.0ではexperimental(実験的)機能である。
Gradleを使っている場合はそれ用のライブラリーを追加する必要がある。
〜
dependencies {
testCompile("org.junit.jupiter:junit-jupiter-api:5.0.0")
testCompile("org.junit.jupiter:junit-jupiter-params:5.0.0") // parameterized tests
testRuntime("org.junit.jupiter:junit-jupiter-engine:5.0.0")
testRuntime("org.junit.platform:junit-platform-launcher:1.0.0") // for IDE
}
import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource;
class ParameterTest { @ParameterizedTest @ValueSource(ints = { 0, 2, 4 }) void evenTrue(int n) { assertTrue(NumberUtil.isEven(n)); } @ParameterizedTest @ValueSource(ints = { 1, 3 }) void evenFalse(int n) { assertFalse(NumberUtil.isEven(n)); } }
パラメーターテストを行う場合は、@Testアノテーションの代わりに@ParameterizedTestアノテーションを付ける。
そして、テストメソッドに、テストで使用する値を受け取る引数を追加しておく。
@ValueSourceアノテーションでテストに使用する値を並べる。
値がintなら引数ints、文字列なら引数stringsで指定する。(両方同時に指定するとエラー)
また、@ValueSourceアノテーションの他にもデータを指定する方法がある。
→junit.orgの3.13. Parameterized Tests
// JUnit4の場合 import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith;
@RunWith(Theories.class) public class ParameterTest { @DataPoints public static int[] VALUES= { 0, 2, 4 }; @Theory public void evenTrue(int n) { assertTrue(NumberUtil.isEven(n)); } }