Create multiple parameter sets in one parameterized class (junit)

后端 未结 8 997
无人共我
无人共我 2021-01-30 13:05

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?

<
8条回答
  •  萌比男神i
    2021-01-30 13:20

    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));
        }
    }
    

提交回复
热议问题