Reputation: 121
How can I test the following method with parameterized testing in JUnit
public class Math {
public static int add(int a, int b) {
return a + b;
}
}
I wish to know how parameterized testing with Junit will be implemented to test this method, when I want to test it with 10 different args.
Upvotes: 1
Views: 289
Reputation: 14520
recently i started zohhak project. i believe it's much cleaner than @Parametrized:
@TestWith({
"25 USD, 7",
"38 GBP, 2",
"null, 0"
})
public void testMethod(Money money, int anotherParameter) {
...
}
Upvotes: 0
Reputation: 301037
The test class must have an annotation @RunWith(Parameterized.class)
and function returning a Collection<Object[]>
should be marked with @Parameters
and a constructor accepting the inputs and the expected output(s)
API: http://junit.sourceforge.net/javadoc/org/junit/runners/Parameterized.html
@RunWith(Parameterized.class)
public class AddTest {
@Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ { 0, 0, 0 }, { 1, 1 ,2},
{ 2, 1, 3 }, { 3, 2, 5 },
{ 4, 3, 7 }, { 5, 5, 10 },
{ 6, 8, 14 } } });
}
private int input1;
private int input2;
private int sum;
public AddTest(int input1, int input2, int sum) {
this.input1= input1;
this.input2= input2;
this.sum = sum;
}
@Test
public void test() {
assertEquals(sum, Math.Add(input1,input2));
}
}
Upvotes: 5