0
0
JUnittesting~10 mins

Why parameterization reduces test duplication in JUnit - Test Execution Impact

Choose your learning style9 modes available
Test Overview

This test uses JUnit parameterization to run the same test logic with different inputs. It verifies that the sum of two numbers matches the expected result. Parameterization helps avoid writing multiple similar tests, reducing duplication.

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

public class CalculatorTest {

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

    @ParameterizedTest
    @MethodSource("provideNumbers")
    void testAddition(int a, int b, int expectedSum) {
        int result = a + b;
        assertEquals(expectedSum, result, "Sum should match expected value");
    }
}
Execution Trace - 7 Steps
StepActionSystem StateAssertionResult
1Test starts and JUnit initializes parameterized test with first input set (1, 2, 3)JUnit test runner ready to execute testAddition with parameters a=1, b=2, expectedSum=3-PASS
2Calculates sum: 1 + 2 = 3Sum calculation doneCheck if calculated sum (3) equals expectedSum (3)PASS
3JUnit runs testAddition with second input set (5, 7, 12)Test runner ready with a=5, b=7, expectedSum=12-PASS
4Calculates sum: 5 + 7 = 12Sum calculation doneCheck if calculated sum (12) equals expectedSum (12)PASS
5JUnit runs testAddition with third input set (10, 0, 10)Test runner ready with a=10, b=0, expectedSum=10-PASS
6Calculates sum: 10 + 0 = 10Sum calculation doneCheck if calculated sum (10) equals expectedSum (10)PASS
7All parameterized tests completed successfullyTest suite finished-PASS
Failure Scenario
Failing Condition: If the sum calculation does not match the expectedSum for any input set
Execution Trace Quiz - 3 Questions
Test your understanding
What does parameterization help avoid in this test?
ARunning tests faster
BUsing assertions
CWriting multiple similar test methods
DImporting libraries
Key Result
Parameterization lets you run the same test logic with different inputs, reducing repeated code and making tests easier to maintain.