Parameterization in JUnit

  

What is Parameterization in JUnit?

Parameterization in JUnit allows you to run the same test multiple times with different inputs. This is useful when you want to test a method using a variety of inputs and expected outputs without duplicating test code.

JUnit provides two main ways to do parameterized testing:

  • In JUnit 4: using @RunWith(Parameterized.class)

  • In JUnit 5: using the @ParameterizedTest annotation from org.junit.jupiter.params



JUnit 4 Parameterized Test

Steps:

  • Annotate the class with @RunWith(Parameterized.class)
  • Create a method annotated with @Parameters to return test data.
  • Define fields to hold parameters.
  • Create a constructor to initialize them.
  • Write your test method using those parameters.


Example:


import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

@RunWith(Parameterized.class)
public class AdditionTest {

    private int a;
    private int b;
    private int expectedSum;

    // Constructor to initialize parameters
    public AdditionTest(int a, int b, int expectedSum) {
        this.a = a;
        this.b = b;
        this.expectedSum = expectedSum;
    }

    // This method provides test data
    @Parameterized.Parameters
    public static Collection<Object[]> testData() {
        return Arrays.asList(new Object[][] {
            {1, 2, 3},
            {5, 3, 8},
            {10, 15, 25},
            {0, 0, 0}
        });
    }

    @Test
    public void testAddition() {
        assertEquals(expectedSum, a + b);
    }
}




JUnit 5 Parameterized Test

Steps:

  • Add dependency for junit-jupiter-params
  • Use @ParameterizedTest annotation.
  • Use @ValueSource@CsvSource, or @MethodSource to provide values.



Example 1: Using @ValueSource


import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class OddNumberTest {

    @ParameterizedTest
    @ValueSource(ints = {1, 3, 5, 7, 9})
    public void testIsOdd(int number) {
        assertTrue(number % 2 != 0);
    }
}





Example 2: Using @CsvSource


import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class AdditionTest {

    @ParameterizedTest
    @CsvSource({
        "1, 2, 3",
        "5, 3, 8",
        "10, 15, 25"
    })
    void testAddition(int a, int b, int expectedSum) {
        assertEquals(expectedSum, a + b);
    }
}




Comparison:


FeatureJUnit 4JUnit 5
Setup@RunWith(Parameterized.class)@ParameterizedTest
Data source@Parameters (method)@ValueSource, @CsvSource, @MethodSource
Constructor requiredYesNo
External data flexibilityLessMore flexible

No comments:

Post a Comment