0Pricing
Testing Mastery: JUnit, Mockito & Integration Tests · 강의

매개변수화 테스트와 동적 테스트

매개변수화 테스트로 여러 데이터 세트를 사용해 실행되는 효율적인 테스트를 작성하고 실행 중에 동적으로 테스트를 생성합니다.

매개변수화 테스트와 동적 테스트은(는) CoddyKit의 무료 Testing Mastery: JUnit, Mockito & Integration Tests 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Testing Mastery: JUnit, Mockito & Integration Tests 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Data-Driven Testing Intro

Imagine you need to test a function with many different inputs. Writing a separate test for each input can be tedious and repetitive.

Data-driven testing allows you to run the same test logic multiple times, but with different sets of data for each run. This makes your tests more efficient and easier to maintain.

What are Parameterized Tests?

Parameterized tests in JUnit 5 let you write a single test method that can be executed multiple times with different arguments. Instead of copying and pasting test code, you supply the data, and JUnit handles the iterations.

  • Saves time and reduces boilerplate code.
  • Improves test coverage by easily testing edge cases.
  • Makes tests more readable and maintainable.

Using @ParameterizedTest

To create a parameterized test, you use the @ParameterizedTest annotation instead of @Test. You also need to provide a source for the arguments.

JUnit 5 offers several argument sources, like @ValueSource for single arguments or @CsvSource for multiple arguments. Let's look at @ValueSource first.

Simple Data with @ValueSource

The @ValueSource annotation is perfect for providing simple, primitive data types directly in your test. It supports strings, ints, longs, doubles, and more.

Each value in the source will cause the test method to run once with that value as an argument.

@ValueSource in Action

Here's a simple example testing if strings are not null or empty. Notice how the test method accepts a String parameter.

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

class StringValidatorTest {

    @ParameterizedTest
    @ValueSource(strings = {"apple", "banana", "orange"})
    void testStringsAreNotEmpty(String fruit) {
        Assertions.assertNotNull(fruit);
        Assertions.assertFalse(fruit.isEmpty());
    }
}

Multiple Args with @CsvSource

When your test method needs more than one argument, @CsvSource comes in handy. It lets you define arguments as comma-separated values (CSV).

Each string in the @CsvSource array represents a row of data, and values are split by commas to match the test method's parameters.

@CsvSource in Action

Let's test a simple addition function. Each line in @CsvSource provides two numbers and their expected sum.

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class CalculatorTest {

    // Simple method to simulate
    int add(int a, int b) {
        return a + b;
    }

    @ParameterizedTest
    @CsvSource({"1, 1, 2", "2, 3, 5", "5, 0, 5"})
    void testAddMethod(int a, int b, int expectedSum) {
        Assertions.assertEquals(expectedSum, add(a, b));
    }
}

Generating Dynamic Tests

Sometimes, the test data or even the number of tests isn't known until runtime. This is where Dynamic Tests shine!

Instead of defining all tests at compile time, dynamic tests allow you to generate them programmatically during test execution. This is useful for complex scenarios or external data sources.

@TestFactory & DynamicTest

To create dynamic tests, you use the @TestFactory annotation. A method annotated with @TestFactory doesn't run a test itself, but rather produces a collection of DynamicTest instances.

  • @TestFactory methods must return a Stream, Collection, Iterable, or Iterator of DynamicTest.
  • Each DynamicTest instance has a display name and an executable lambda.

Dynamic Test in Action

Here's an example generating tests for string lengths. Each test is created on the fly based on a list of words.

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;

import java.util.Arrays;
import java.util.Collection;

class DynamicTestExample {

    @TestFactory
    Collection<DynamicTest> dynamicTestsFromCollection() {
        return Arrays.asList(
            DynamicTest.dynamicTest("Test 'apple' length",
                () -> Assertions.assertEquals(5, "apple".length())),
            DynamicTest.dynamicTest("Test 'banana' length",
                () -> Assertions.assertEquals(6, "banana".length())),
            DynamicTest.dynamicTest("Test 'cat' length",
                () -> Assertions.assertEquals(3, "cat".length()))
        );
    }
}

Parameterized vs. Dynamic

Parameterized and Dynamic tests both help reduce boilerplate, but they serve different needs.

Which of the following is the primary benefit of using Parameterized Tests over writing individual @Test methods for similar test cases?

Recap: Flexible Testing

Great job! You've learned how to make your JUnit tests more flexible and efficient:

  • Parameterized Tests (@ParameterizedTest with sources like @ValueSource, @CsvSource) allow you to run the same test logic with multiple, predefined data sets.
  • Dynamic Tests (@TestFactory) let you generate tests programmatically at runtime, ideal for scenarios where test cases are discovered dynamically.

These features help you write cleaner, more comprehensive tests with less effort!

자주 묻는 질문

“매개변수화 테스트와 동적 테스트” 강의는 무료인가요?

네 — “매개변수화 테스트와 동적 테스트” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Testing Mastery: JUnit, Mockito & Integration Tests 강의 전체를 잠금 해제할 수 있습니다. Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 총 4개의 강의가 포함되어 있습니다.

“매개변수화 테스트와 동적 테스트”에서 뭘 배우나요?

매개변수화 테스트로 여러 데이터 세트를 사용해 실행되는 효율적인 테스트를 작성하고 실행 중에 동적으로 테스트를 생성합니다. 브라우저에서 직접 실행하는 실습 코드로 Testing Mastery: JUnit, Mockito & Integration Tests을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Testing Mastery: JUnit, Mockito & Integration Tests을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Testing Mastery: JUnit, Mockito & Integration Tests은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“매개변수화 테스트와 동적 테스트” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Testing Mastery: JUnit, Mockito & Integration Tests 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Testing Mastery: JUnit, Mockito & Integration Tests 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 테스트 수명 주기 및 순서
  2. 매개변수화 테스트와 동적 테스트
  3. 예외 테스트 및 시간 제한
  4. 조건부 테스트와 가정
← Testing Mastery: JUnit, Mockito & Integration Tests(으)로 돌아가기