JUnit test with dynamic number of tests

前端 未结 7 642
灰色年华
灰色年华 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:01

    Junit 5 Parameterized Tests

    JUnit 5 parameterized tests support this by allowing the use of a method as data source:

    @ParameterizedTest
    @MethodSource("fileProvider")
    void testFile(File f) {
        // Your test comes here
    }
    
    static Stream fileProvider() {
        return Arrays.asList(new File(".").list()).stream();
    }
    

    JUnit 5 DynamicTests

    JUnit 5 also supports this through the notion of a DynamicTest, which is to be generated in a @TestFactory, by means of the static method dynamicTest.

    import org.junit.jupiter.api.DynamicTest;
    import org.junit.jupiter.api.TestFactory;
    import static org.junit.jupiter.api.DynamicTest.dynamicTest;
    
    import java.util.stream.Stream;
    
    @TestFactory
    public Stream testFiles() {
        return Arrays.asList(new File(".").list())
                .stream()
                .map((file) -> dynamicTest(
                        "Test for file: " + file,
                        () -> { /* Your test comes here */ }));
    }
    

    The tests run in your IDE (IntelliJ here) will be displayed like this:

提交回复
热议问题