Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JUnit test with dynamic number of tests

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 the TestCase this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. How can I write a TestCase / TestSuite such that each file shows up as a separate test e.g. in the graphical TestRunner of Eclipse? (Coding an explicit test method for each file is not an option.)

Compare also the question ParameterizedTest with a name in Eclipse Testrunner.

like image 951
Hans-Peter Störr Avatar asked Dec 11 '08 09:12

Hans-Peter Störr


People also ask

What is dynamic test in JUnit?

1. Junit 5 Dynamic tests. A dynamic test is a test that generated at runtime by factory method using @TestFactory annotation. The method marked @TestFactory is not a test case, rather it's a factory for test cases.

Is JUnit testing static or dynamic?

JUnit Dynamic Tests JUnit @TestFactory methods must not be private or static. These methods must return a Stream, Collection, Iterable, or Iterator of DynamicNode instances.

Is JUnit 5 faster than junit4?

JUnit 5 is 10x slower than JUnit 4 #880.


1 Answers

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<Object[]> data() {         // load the files as you want         Object[] fileArg1 = new Object[] { new File("path1") };         Object[] fileArg2 = new Object[] { new File("path2") };          Collection<Object[]> data = new ArrayList<Object[]>();         data.add(fileArg1);         data.add(fileArg2);         return data;     } } 

Also check this example

like image 74
bruno conde Avatar answered Oct 03 '22 12:10

bruno conde