JUnit test with dynamic number of tests

前端 未结 7 631
灰色年华
灰色年华 2020-11-30 18:42

In our project I have several JUnit tests that e.g. take every file from a directory and run a test on it. If I implement a testEveryFileInDirectory method in t

7条回答
  •  渐次进展
    2020-11-30 19:18

    Take a look at Parameterized Tests in JUnit 4.

    Actually I did this a few days ago. I'll try to explain ...

    First build your test class normally, as you where just testing with one input file. Decorate your class with:

    @RunWith(Parameterized.class)
    

    Build one constructor that takes the input that will change in every test call (in this case it may be the file itself)

    Then, build a static method that will return a Collection of arrays. Each array in the collection will contain the input arguments for your class constructor e.g. the file. Decorate this method with:

    @Parameters
    

    Here's a sample class.

    @RunWith(Parameterized.class)
    public class ParameterizedTest {
    
        private File file;
    
        public ParameterizedTest(File file) {
            this.file = file;
        }
    
        @Test
        public void test1() throws Exception {  }
    
        @Test
        public void test2() throws Exception {  }
    
        @Parameters
        public static Collection data() {
            // load the files as you want
            Object[] fileArg1 = new Object[] { new File("path1") };
            Object[] fileArg2 = new Object[] { new File("path2") };
    
            Collection data = new ArrayList();
            data.add(fileArg1);
            data.add(fileArg2);
            return data;
        }
    }
    

    Also check this example

提交回复
热议问题