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

Parameterized and Dynamic Tests

Write efficient tests that run with multiple data sets using parameterized tests and generate tests dynamically at runtime.

Parameterized and Dynamic Tests is a free Testing Mastery: JUnit, Mockito & Integration Tests lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Testing Mastery: JUnit, Mockito & Integration Tests learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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!

Frequently asked questions

Is the “Parameterized and Dynamic Tests” lesson free?

Yes — the full text of “Parameterized and Dynamic Tests” is free to read here on the web, and the Testing Mastery: JUnit, Mockito & Integration Tests course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Testing Mastery: JUnit, Mockito & Integration Tests course, upgrade to CoddyKit PRO.

What will I learn in “Parameterized and Dynamic Tests”?

Write efficient tests that run with multiple data sets using parameterized tests and generate tests dynamically at runtime. You practise Testing Mastery: JUnit, Mockito & Integration Tests with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Testing Mastery: JUnit, Mockito & Integration Tests?

No prior experience is required. Testing Mastery: JUnit, Mockito & Integration Tests on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Parameterized and Dynamic Tests” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Testing Mastery: JUnit, Mockito & Integration Tests lesson?

Yes. Every Testing Mastery: JUnit, Mockito & Integration Tests lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Test Lifecycle and Ordering
  2. Parameterized and Dynamic Tests
  3. Exception Testing & Timeouts
  4. Conditional Tests and Assumptions
← Back to Testing Mastery: JUnit, Mockito & Integration Tests