@MethodSource helps you run the same test with different data easily. It uses a method that gives test data, so you don't repeat code.
0
0
@MethodSource for factory methods in JUnit
Introduction
You want to test a function with many input values without writing many test methods.
You have complex test data that is easier to create in a method than inline.
You want to keep your test data separate from your test logic for clarity.
You want to reuse the same test data for multiple tests.
You want to generate test data dynamically or from calculations.
Syntax
JUnit
@ParameterizedTest @MethodSource("factoryMethodName") void testMethod(Type param) { // test code } static Stream<Type> factoryMethodName() { return Stream.of(data1, data2, ...); }
The factory method must be static and return a Stream, Iterable, Iterator, or array of arguments.
The method name in @MethodSource is a string matching the factory method's name.
Examples
This example tests a method with three different strings.
JUnit
@ParameterizedTest @MethodSource("stringProvider") void testWithStrings(String arg) { assertNotNull(arg); } static Stream<String> stringProvider() { return Stream.of("apple", "banana", "cherry"); }
This example tests that numbers are positive using a factory method.
JUnit
@ParameterizedTest @MethodSource("intProvider") void testWithInts(int number) { assertTrue(number > 0); } static Stream<Integer> intProvider() { return Stream.of(1, 2, 3, 4); }
Sample Program
This test uses @MethodSource to supply three sets of numbers to test the add method of Calculator.
JUnit
import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.Arguments; import java.util.stream.Stream; public class CalculatorTest { @ParameterizedTest @MethodSource("additionProvider") void testAdd(int a, int b, int expected) { Calculator calc = new Calculator(); assertEquals(expected, calc.add(a, b)); } static Stream<Arguments> additionProvider() { return Stream.of( Arguments.of(1, 1, 2), Arguments.of(2, 3, 5), Arguments.of(10, 20, 30) ); } } class Calculator { int add(int x, int y) { return x + y; } }
OutputSuccess
Important Notes
Factory methods must be static so JUnit can call them without creating an instance.
You can return multiple parameters using Arguments.of(...) inside the Stream.
Use descriptive method names for clarity in test reports.
Summary
@MethodSource lets you run one test with many data sets easily.
Factory methods provide the test data and must be static.
This keeps tests clean and avoids repeating similar test code.