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

参数化测试与动态测试

使用参数化测试运行多组数据,并在运行时动态生成测试,从而编写高效的测试。

参数化测试与动态测试 是 CoddyKit 上的免费 Testing Mastery: JUnit, Mockito & Integration Tests 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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!

常见问题解答

「参数化测试与动态测试」课时是免费的吗?

是的 — 「参数化测试与动态测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Testing Mastery: JUnit, Mockito & Integration Tests 课程的其余内容,请升级到 CoddyKit PRO。 Testing Mastery: JUnit, Mockito & Integration Tests 课程共包含 4 节课。

「参数化测试与动态测试」这节课中我会学到什么?

使用参数化测试运行多组数据,并在运行时动态生成测试,从而编写高效的测试。 你通过在浏览器中直接运行的动手代码来练习 Testing Mastery: JUnit, Mockito & Integration Tests,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Testing Mastery: JUnit, Mockito & Integration Tests 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Testing Mastery: JUnit, Mockito & Integration Tests 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「参数化测试与动态测试」课时需要多长时间?

大多数 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