Параметризованные и динамические тесты
Пишите эффективные тесты, выполняемые с несколькими наборами данных, используя параметризованные тесты, и динамически создавайте тесты во время выполнения.
«Параметризованные и динамические тесты» — бесплатный урок Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения 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.
@TestFactorymethods must return aStream,Collection,Iterable, orIteratorofDynamicTest.- Each
DynamicTestinstance 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 (
@ParameterizedTestwith 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) и разблокировать остальной курс Testing Mastery: JUnit, Mockito & Integration Tests, подпишись на CoddyKit PRO. Курс Testing Mastery: JUnit, Mockito & Integration Tests содержит 4 уроков всего.
Чему я научусь в уроке «Параметризованные и динамические тесты»?
Пишите эффективные тесты, выполняемые с несколькими наборами данных, используя параметризованные тесты, и динамически создавайте тесты во время выполнения. Ты практикуешь Testing Mastery: JUnit, Mockito & Integration Tests с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.
Нужен ли мне опыт, чтобы начать Testing Mastery: JUnit, Mockito & Integration Tests?
Предыдущий опыт не требуется. Testing Mastery: JUnit, Mockito & Integration Tests на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.
Сколько времени занимает урок «Параметризованные и динамические тесты»?
Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.
Можно ли писать и запускать код в этом уроке Testing Mastery: JUnit, Mockito & Integration Tests?
Да. Каждый урок Testing Mastery: JUnit, Mockito & Integration Tests включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.
Все уроки этого курса
- Жизненный цикл и порядок тестов
- Параметризованные и динамические тесты
- Тестирование исключений и ограничения времени
- Условные тесты и предположения