Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Parameterized tests in JUnit Parameterized tests in JUnit can be very useful when writing tests based on tabular data. These type of tests can save you from writing a lot of duplicate or boilerplate code. While there is a fair amount of articles on the subject on the Internet, I wasn’t able to find a code sample that you can simply copy into you…
package com.empoweragile;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
@RunWith(Parameterized.class)
public class AddtionTest {
// since junit 4.11
@Parameterized.Parameters(name = "Addition test: {0}+{1}={2}. Test n° {index}")
public static Iterable<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 2, 2, 5 },
{ -2, -2, -4 },
{ 2, 0, 2 },
{ -5, 0, -6 },
{ -3, 3, 0 },
});
}
private final int left;
private final int right;
private final int expected;
public AddtionTest(int left, int right, int expected) {
this.left = left;
this.right = right;
this.expected = expected;
}
@Test
public void testAddition() {
Math math = new Math();
assertEquals(expected, math.add(left, right));
}
}
class Math {
public int add(int left, int right) {
return left + right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment