Welcome to the JUnit Parameterized Tests lesson! This tutorial will empower you to write efficient and flexible tests using the powerful JUnit library in Java. Let's dive in!
Parameterized tests are a handy feature of JUnit that allows you to test a single test method with multiple sets of input parameters. This significantly reduces the effort required to write multiple test methods for different test cases.
Parameterized tests help save time and effort by reducing the need to create multiple test methods for different test cases. They make it easier to maintain and manage tests, especially when dealing with test data that may change over time.
To create a parameterized test, you'll need the junit-vintage-engine and ParameterizedRunner dependencies. Add them to your Maven or Gradle project.
<dependency>
<groupId>junit</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit-vintage</groupId>
<artifactId>junit-vintage-parameterized</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>Now let's create a parameterized test using a simple calculator example.
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.param.Parameters;
import org.junit.Test;
import static org.junit.Assert.*;
@RunWith(Parameterized.class)
public class CalculatorTest {
private int a;
private int b;
private int expectedResult;
public CalculatorTest(int a, int b, int expectedResult) {
this.a = a;
this.b = b;
this.expectedResult = expectedResult;
}
@Parameters(name = "Testing: {0} + {1} = {2}")
public static Iterable<Object[]> data() {
return new Object[][]{
{1, 2, 3},
{5, 3, 8},
{-2, -3, 5}
};
}
@Test
public void testAddition() {
Calculator calculator = new Calculator();
int result = calculator.add(a, b);
assertEquals(expectedResult, result);
}
}
class Calculator {
public int add(int a, int b) {
return a + b;
}
}In this example, we have a CalculatorTest class that contains a parameterized test called testAddition. The data() method returns a list of input test cases, each represented as an array of three integers. The CalculatorTest constructor accepts these integers as parameters.
To run the parameterized test, simply run your test class as you would any other JUnit test.
mvn test
Or, if you're using an IDE like IntelliJ IDEA or Eclipse, you can run the test from the IDE.
@ValueSource and @NullSource to generate test data dynamically.@Before, @After, and @BeforeEach to set up and clean up test data.What is the advantage of using parameterized tests over traditional tests?
Happy learning, and let's code together! 🤝🏼