1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

パラメータ化テストの使い分け

1
Posted at

JUnit 5 のパラメータ化テストでは、テストデータの構造や数に応じてアノテーションを使い分けられます。

基本的な違い

アノテーション 用途 特徴
@ValueSource 単一引数 intString などの単一の値を複数回テストする場合に最適。
@CsvSource 複数引数 「入力値と期待値」のように、関連する複数の値をセットで渡す場合に最適。

@ValueSource(単一の値)

1回のテストに対して、一つの引数(単一値)を順番に渡して実行します。

@ParameterizedTest
@ValueSource(ints = {1, 2, 3})
void testOneArg(int n) {
    assertTrue(n > 0);
}

@CsvSource(複数の関連する値)

カンマ区切りの文字列を使って、複数の引数を同時に渡せます。JUnitが自動的に型変換(Stringからintなど)を行ってくれます。

@ParameterizedTest
@CsvSource({
    "1, true",
    "0, false",
    "-1, false"
})

void testMultipleArgs(int input, boolean expected) {
    assertEquals(expected, input > 0);
}

より複雑なデータには @MethodSource が使えます。
引数がリストや複雑なオブジェクト、または動的に生成されるデータの場合は、メソッドから値を供給できます。

@ParameterizedTest
@MethodSource("provideStrings")
void testWithMethodSource(String argument) {
    assertNotNull(argument);
}

static Stream<String> provideStrings() {
    return Stream.of("apple", "banana");
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?