@ArgumentsSource with custom providers in JUnit - Build an Automation Script
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.ArgumentsSource; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.params.provider.ArgumentsProvider; import java.util.stream.Stream; public class CustomArgumentsSourceTest { static class MyArgumentsProvider implements ArgumentsProvider { @Override public Stream<? extends Arguments> provideArguments(ExtensionContext context) { return Stream.of( Arguments.of("apple", 5), Arguments.of("banana", 6), Arguments.of("cherry", 6) ); } } @ParameterizedTest @ArgumentsSource(MyArgumentsProvider.class) void testWithCustomArgumentsSource(String fruit, int length) { Assertions.assertEquals(length, fruit.length()); } }
The code defines a test class CustomArgumentsSourceTest with a nested static class MyArgumentsProvider that implements ArgumentsProvider. This provider returns a stream of argument sets, each containing a fruit name and its expected length.
The test method testWithCustomArgumentsSource is annotated with @ParameterizedTest and @ArgumentsSource(MyArgumentsProvider.class). This tells JUnit to run the test multiple times, once for each argument set provided by MyArgumentsProvider.
Inside the test method, an assertion checks that the length of the fruit string matches the expected length. This verifies that the arguments are passed correctly.
This approach keeps test data separate from the test logic, making tests clean and maintainable.
Now add data-driven testing with 3 different sets of fruit names and their lengths using the custom ArgumentsProvider