Currently I have to create a parameterized test class for every method that I want to test with several different inputs. Is there a way to add this together in one file?
<
Well, now JUnit-5 offers you a solution for this - by redefining a way to write parameterized tests. Now a parameterized test can be defined at a method level using @ParameterizedTest and can be given a method source using @MethodSource.
So in your case you can have 2 separate data source methods for providing input data for your add() and subtract() test methods, both in the same class. Your code should go something like this:
public class CalculatorTest{
public static int[][] dataSetForAdd() {
return new int[][] { { 1 , 2, 3 }, { 2, 4, 6 }, { 121, 4, 125 } };
}
public static int[][] dataSetForSubtract() {
return new int[][] { { 1 , 2, -1 }, { 2, 4, -2 }, { 121, 4, 117 } };
}
@ParameterizedTest
@MethodSource(names = "dataSetForAdd")
void testCalculatorAddMethod(int[] dataSetForAdd) {
Calculator calculator= new Calculator();
int m1 = dataSetForAdd[0];
int m2 = dataSetForAdd[1];
int expected = dataSetForAdd[2];
assertEquals(expected, calculator.add(m1, m2));
}
@ParameterizedTest
@MethodSource(names = "dataSetForSubtract")
void testCalculatorAddMethod(int[] dataSetForSubtract) {
Calculator calculator= new Calculator();
int m1 = dataSetForSubtract[0];
int m2 = dataSetForSubtract[1];
int expected = dataSetForSubtract[2];
assertEquals(expected, calculator.subtract(m1, m2));
}
}