Create multiple parameter sets in one parameterized class (junit)

后端 未结 8 934
无人共我
无人共我 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条回答
  •  面向向阳花
    2021-01-30 13:21

    This answer is similar to Tarek's one (the parametrized part), although I think it is a bit more extensible. Also solves your problem and you won't have failed tests if everything is correct:

    @RunWith(Parameterized.class)
    public class CalculatorTest {
        enum Type {SUBSTRACT, ADD};
        @Parameters
        public static Collection data(){
            return Arrays.asList(new Object[][] {
              {Type.SUBSTRACT, 3.0, 2.0, 1.0},
              {Type.ADD, 23.0, 5.0, 28.0}
            });
        }
    
        private Type type;
        private Double a, b, expected;
    
        public CalculatorTest(Type type, Double a, Double b, Double expected){
            this.type = type;
            this.a=a; this.b=b; this.expected=expected;
        }
    
        @Test
        public void testAdd(){
            Assume.assumeTrue(type == Type.ADD);
            assertEquals(expected, Calculator.add(a, b));
        }
    
        @Test
        public void testSubstract(){
            Assume.assumeTrue(type == Type.SUBSTRACT);
            assertEquals(expected, Calculator.substract(a, b));
        }
    }
    

提交回复
热议问题