0
0
JUnittesting~10 mins

@ArgumentsSource with custom providers in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test uses JUnit's @ArgumentsSource annotation with a custom provider to supply multiple sets of arguments. It verifies that the tested method correctly processes each input and produces the expected output.

Test Code - JUnit 5
JUnit
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 CustomProvider implements ArgumentsProvider {
        @Override
        public Stream<? extends Arguments> provideArguments(ExtensionContext context) {
            return Stream.of(
                Arguments.of(2, 4),
                Arguments.of(3, 9),
                Arguments.of(4, 16)
            );
        }
    }

    @ParameterizedTest
    @ArgumentsSource(CustomProvider.class)
    void testSquareFunction(int input, int expected) {
        int actual = input * input;
        Assertions.assertEquals(expected, actual, "Square calculation failed");
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initialized-PASS
2JUnit identifies @ParameterizedTest with @ArgumentsSource(CustomProvider.class)Test method 'testSquareFunction' ready to run with arguments from CustomProvider-PASS
3CustomProvider.provideArguments() called to supply test argumentsStream of Arguments: (2,4), (3,9), (4,16)-PASS
4Test method invoked with input=2, expected=4Calculating 2 * 2Assert actual (4) equals expected (4)PASS
5Test method invoked with input=3, expected=9Calculating 3 * 3Assert actual (9) equals expected (9)PASS
6Test method invoked with input=4, expected=16Calculating 4 * 4Assert actual (16) equals expected (16)PASS
7All parameterized test cases completedTest run summary available-PASS
Failure Scenario
Failing Condition: The actual square calculation does not match the expected value for any input
Execution Trace Quiz - 3 Questions
Test your understanding
What does the CustomProvider class do in this test?
ASupplies multiple sets of arguments to the test method
BRuns the test method multiple times automatically
CDefines the test method to be executed
DChecks the assertion results
Key Result
Using a custom ArgumentsProvider with @ArgumentsSource allows flexible and reusable test data provisioning for parameterized tests, improving test coverage and maintainability.