0
0
JUnittesting~15 mins

@MethodSource for factory methods in JUnit - Build an Automation Script

Choose your learning style9 modes available
Automate a parameterized test using @MethodSource factory method
Preconditions (2)
Step 1: Create a static factory method that returns a Stream of Arguments
Step 2: Annotate the test method with @ParameterizedTest and @MethodSource referencing the factory method
Step 3: Write the test method to accept parameters from the factory method
Step 4: Run the test and verify it executes once per data set
✅ Expected Result: The test runs multiple times, once for each data set provided by the factory method, and all assertions pass
Automation Requirements - JUnit 5
Assertions Needed:
Verify the test method runs for each input from the factory method
Assert expected output for each input parameter
Best Practices:
Use static factory methods returning Stream<Arguments>
Name factory methods clearly and reference them correctly in @MethodSource
Keep test methods simple and focused on one assertion per parameter set
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals;
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 {

    static Stream<Arguments> provideAddInputs() {
        return Stream.of(
            Arguments.of(1, 2, 3),
            Arguments.of(5, 7, 12),
            Arguments.of(-1, 1, 0)
        );
    }

    @ParameterizedTest
    @MethodSource("provideAddInputs")
    void testAdd(int a, int b, int expectedSum) {
        Calculator calculator = new Calculator();
        int result = calculator.add(a, b);
        assertEquals(expectedSum, result, () -> "Sum of " + a + " and " + b + " should be " + expectedSum);
    }
}

class Calculator {
    int add(int x, int y) {
        return x + y;
    }
}

The static method provideAddInputs is the factory method that returns a Stream<Arguments>. Each Arguments.of() call provides one set of parameters for the test.

The test method testAdd is annotated with @ParameterizedTest and @MethodSource referencing the factory method by name. It accepts parameters matching the factory method's arguments.

Inside the test, we create a Calculator instance and call the add method with the parameters. Then we assert the result equals the expected sum.

This setup runs the test three times, once per data set, verifying the addition logic for different inputs.

Common Mistakes - 4 Pitfalls
Factory method is not static
Factory method returns List instead of Stream
Incorrect method name in @MethodSource annotation
Test method parameters do not match factory method arguments
Bonus Challenge

Now add data-driven testing with 3 different inputs for a subtraction method using @MethodSource

Show Hint