Skip to content

Instantly share code, notes, and snippets.

@darsen
Last active December 14, 2015 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save darsen/5104291 to your computer and use it in GitHub Desktop.
Save darsen/5104291 to your computer and use it in GitHub Desktop.
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