0
0
JUnittesting~10 mins

Custom argument providers in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses a custom argument provider to supply multiple sets of input data to a parameterized test method. It verifies that the sum of two integers matches the expected result for each data set.

Test Code - JUnit 5
JUnit
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.ArgumentsProvider;
import org.junit.jupiter.params.provider.ArgumentsSource;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.assertEquals;

class CustomArgumentProviderTest {

    static class SumArgumentsProvider implements ArgumentsProvider {
        @Override
        public Stream<Arguments> provideArguments(ExtensionContext context) {
            return Stream.of(
                Arguments.of(1, 2, 3),
                Arguments.of(5, 7, 12),
                Arguments.of(10, 15, 25)
            );
        }
    }

    @ParameterizedTest
    @ArgumentsSource(SumArgumentsProvider.class)
    void testSum(int a, int b, int expectedSum) {
        int actualSum = a + b;
        assertEquals(expectedSum, actualSum, () -> String.format("Sum of %d and %d should be %d", a, b, expectedSum));
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test runner starts and identifies the parameterized test method with custom argument providerJUnit test environment initialized, SumArgumentsProvider ready to supply arguments-PASS
2SumArgumentsProvider.provideArguments() is called to get test data streamStream of argument sets [(1,2,3), (5,7,12), (10,15,25)] prepared-PASS
3Test method testSum is invoked with arguments (1, 2, 3)Test method running with a=1, b=2, expectedSum=3assertEquals(3, 1+2)PASS
4Test method testSum is invoked with arguments (5, 7, 12)Test method running with a=5, b=7, expectedSum=12assertEquals(12, 5+7)PASS
5Test method testSum is invoked with arguments (10, 15, 25)Test method running with a=10, b=15, expectedSum=25assertEquals(25, 10+15)PASS
6All parameterized test invocations complete, test run endsAll assertions passed for all argument sets-PASS
Failure Scenario
Failing Condition: One of the expected sums does not match the actual sum of the inputs
Execution Trace Quiz - 3 Questions
Test your understanding
What does the custom argument provider supply to the test method?
AThe test report format
BMultiple sets of input arguments for the test
CThe test method's return values
DThe test method's annotations
Key Result
Using a custom argument provider helps run the same test logic with different data sets, improving test coverage and reducing code duplication.