5.1 @ParameterizedTest 주석

때로는 다른 매개변수(다른 값, 다른 입력 매개변수, 다른 사용자 이름)를 사용하여 테스트를 여러 번 호출하기를 원할 수도 있습니다. JUnit은 삶을 더 쉽게 만드는 것을 목표로 하므로 이 경우에는 매개변수화된 테스트와 같은 것이 있습니다.

매개변수화된 테스트를 사용하려면 다음에 하나 이상의 종속성을 추가해야 합니다 pom.xml.

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-params</artifactId>
    <version>5.8.2</version>
    <scope>test</scope>
</dependency>

그런 다음 예를 고려할 수 있습니다.

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethod(int argument) {
    //test code
}

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethodWithAutoboxing(Integer argument) {
    //test code
}

각 테스트 메서드는 3번 호출되며 호출될 때마다 다른 매개변수가 전달됩니다. 값은 다른 주석인 @ValueSource를 사용하여 설정됩니다 . 그러나 그것에 대해 더 말할 필요가 있습니다.

5.2 @ValueSource 주석

@ValueSource 주석은 프리미티브 및 리터럴 작업에 적합합니다. 쉼표로 구분된 매개 변수 값을 나열하면 각 값에 대해 테스트가 한 번 호출됩니다.

@ParameterizedTest
@ValueSource(ints = { 1, 2, 3 })
void testMethodWithAutoboxing(Integer argument) {
    //test code
}

그러나 마이너스도 있습니다. 이 주석은 null을 지원하지 않으므로 @NullSource 라는 특별한 버팀목을 사용해야 합니다 . 다음과 같습니다.

@ParameterizedTest
@NullSource
void testMethodNullSource(Integer argument) {
    assertTrue(argument == null);
}

5.3 @EnumSource 주석

특정 Enum의 모든 값을 메서드에 전달하는 특수 주석 @EnumSource 도 있습니다 . 응용 프로그램은 다음과 같습니다.

enum Direction {
    EAST, WEST, NORTH, SOUTH
}

@ParameterizedTest
@EnumSource(Direction.class)
void testWithEnumSource(Direction d) {
    assertNotNull(d);
}

5.4 @MethodSource 주석

그러나 개체를 매개 변수로 전달하는 방법은 무엇입니까? 특히 복잡한 구성 알고리즘이 있는 경우. 이렇게 하려면 해당 값의 목록(Stream)을 반환하는 특수 도우미 메서드를 지정하기만 하면 됩니다.

예:

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

static Stream<String> argsProviderFactory() {
    return Stream.of("one", "two",  "three");
}

인수가 여러 개인 매개변수화된 테스트

물론 메서드에 여러 매개 변수를 전달하려는 경우 어떻게 해야 할지 이미 궁금했을 것입니다. 이에 대한 매우 멋진 @CSVSource 주석이 있습니다 . 쉼표로 구분된 메소드 매개변수의 값을 나열할 수 있습니다.

예:

@ParameterizedTest
@CsvSource({
    "alex, 30, Programmer, Working",
    "brian, 35, Tester, Working",
	"charles, 40, manager, kicks"
})
void testWithCsvSource(String name, int age, String occupation, String status) {
	//method code
}