Using multiple parameter types lets you test a method with different kinds of inputs in one test. This helps find bugs faster and saves time.
0
0
Multiple parameter types in JUnit
Introduction
You want to test a method that takes more than one input value.
You want to check how a method behaves with different combinations of inputs.
You want to avoid writing many similar test methods for different input types.
You want to improve test coverage by testing various input scenarios.
You want to keep your test code clean and organized.
Syntax
JUnit
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; class TestClass { @ParameterizedTest @CsvSource({ "input1, 10", "input2, 20" }) void testMethod(String param1, int param2) { // test code here } }
@ParameterizedTest marks the test to run multiple times with different inputs.
@CsvSource provides pairs of values separated by commas for each test run.
Examples
This test checks the length of different fruit names using a String and an int parameter.
JUnit
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; class FruitTest { @ParameterizedTest @CsvSource({ "apple, 5", "banana, 6" }) void testFruitLength(String fruit, int length) { assertEquals(length, fruit.length()); } }
This test checks if the sum of two integers matches the expected result.
JUnit
import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertEquals; class SumTest { @ParameterizedTest @CsvSource({ "10, 20, 30", "5, 15, 20" }) void testSum(int a, int b, int expectedSum) { assertEquals(expectedSum, a + b); } }
Sample Program
This test runs the add method with three sets of integer inputs and checks if the sum is correct each time.
JUnit
import static org.junit.jupiter.api.Assertions.assertEquals; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; public class CalculatorTest { @ParameterizedTest @CsvSource({ "2, 3, 5", "10, 20, 30", "5, 7, 12" }) void testAdd(int a, int b, int expected) { Calculator calc = new Calculator(); assertEquals(expected, calc.add(a, b)); } } class Calculator { int add(int x, int y) { return x + y; } }
OutputSuccess
Important Notes
Use @CsvSource for simple multiple parameters separated by commas.
Ensure parameter types in the test method match the types in the CsvSource.
Each line in @CsvSource represents one test run with its parameters.
Summary
Multiple parameter types let you test methods with different inputs easily.
@ParameterizedTest with @CsvSource is a simple way to provide multiple inputs.
This approach saves time and improves test coverage.