How to attach a DataPoint with a Theory?

后端 未结 4 965
無奈伤痛
無奈伤痛 2021-02-18 23:59
@DataPoints public static final Integer[] input1={1,2};
@Theory
@Test
public void test1(int input1){

}

@DataPoints public static final Integer[] input2={3,4};
@Theory
         


        
4条回答
  •  一整个雨季
    2021-02-19 00:44

    DataPoints apply to the class. If you have a @Theory method which takes an int, and you have a DataPoint which is an array of ints, then it will be called with the int.

    @RunWith(Theories.class)
    public class TheoryTest {
        @DataPoint public static int input1 = 45;
        @DataPoint public static int input2 = 46;
        @DataPoints public static String[] inputs = new String[] { "foobar", "barbar" };
    
        @Theory public void testString1(String input) {
            System.out.println("testString1 input=" + input);
        }
    
        @Theory public void testString2(String input) {
            System.out.println("testString2 input=" + input);
        }
    
        @Theory public void test1(int input) {
            System.out.println("test1 input=" + input);
        }
    
        @Theory public void test2(int input) {
            System.out.println("test2 input=" + input);
        }
    }
    

    This calls test1 with 45 & 46, and test2 with 45 & 46. It calls testString1 with "foobar" and "barbar" and testString2 with "foobar" and "barbar".

    If you really want to use different data sets for different theories, you can wrap the data in a private class:

    @RunWith(Theories.class)
    public class TheoryTest {
        public static class I1 { int i; public I1(int i) { this.i = i;} }
        public static class I2 { int i; public I2(int i) { this.i = i;} }
    
        @DataPoint public static I1 input1 = new I1(45);
        @DataPoint public static I2 input2 = new I2(46);
    
        @Theory
        public void test1(I1 input) {
            System.out.println("test1 input=" + input.i);
        }
    
        @Theory
        public void test2(I2 input) {
            System.out.println("test2 input=" + input.i);
        }
    }
    

    This calls test1 with 45 and test2 with 46. This works, but in my opinion, it obscures the code, and it may be a better solution to just split the Test class into two classes.

提交回复
热议问题