Tests paramétrés et dynamiques
Écrivez des tests efficaces qui s'exécutent avec plusieurs ensembles de données grâce aux tests paramétrés, et générez dynamiquement des tests à l'exécution.
Tests paramétrés et dynamiques est une leçon Testing Mastery: JUnit, Mockito & Integration Tests gratuite sur CoddyKit. Ceci est la leçon 2 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Testing Mastery: JUnit, Mockito & Integration Tests, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Testing Mastery: JUnit, Mockito & Integration Tests comprend 4 leçons au total.
Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.
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!
Questions Fréquemment Posées
La leçon « Tests paramétrés et dynamiques » est-elle gratuite ?
Oui — le texte complet de « Tests paramétrés et dynamiques » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Testing Mastery: JUnit, Mockito & Integration Tests, passe à CoddyKit PRO. Le cours Testing Mastery: JUnit, Mockito & Integration Tests comprend 4 leçons au total.
Qu'est-ce que j'apprendrai dans « Tests paramétrés et dynamiques » ?
Écrivez des tests efficaces qui s'exécutent avec plusieurs ensembles de données grâce aux tests paramétrés, et générez dynamiquement des tests à l'exécution. Tu pratiques Testing Mastery: JUnit, Mockito & Integration Tests avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.
Dois-je avoir de l'expérience pour commencer Testing Mastery: JUnit, Mockito & Integration Tests ?
Aucune expérience préalable n'est requise. Testing Mastery: JUnit, Mockito & Integration Tests sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 2 sur 4.
Combien de temps prend la leçon « Tests paramétrés et dynamiques » ?
La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.
Peux-tu écrire et exécuter du code dans cette leçon Testing Mastery: JUnit, Mockito & Integration Tests ?
Oui. Chaque leçon Testing Mastery: JUnit, Mockito & Integration Tests inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.
Toutes les leçons de ce cours
- Cycle de vie et ordre d'exécution des tests
- Tests paramétrés et dynamiques
- Tests d'exceptions et délais d'attente
- Tests conditionnels et hypothèses