Reputation: 36853
I used to write JUnit tests as methods, such as:
public class TextualEntailerTest {
@Test test1() {...}
@Test test2() {...}
@Test test3() {...}
}
Since most of the test cases has a similar structure, I decided to be "data-driven", and put the contents of the tests in XML files. So, I created a method "testFromFile(file)" and changed my test to:
public class TextualEntailerTest {
@Test test1() { testFromFile("test1.xml"); }
@Test test2() { testFromFile("test2.xml"); }
@Test test3() { testFromFile("test3.xml"); }
}
As I add more and more tests, I become tired of adding a line for each new test file I add. Of course I can put all files in a single test:
public class TextualEntailerTest {
@Test testAll() {
foreach (String file: filesInFolder)
testFromFile(file);
}
}
However, I prefer that each file will be a separate test, because this way JUnit gives nice statistics about the number of files passed and failed.
So, my question is: how to tell JUnit to run separate tests, where each test is of the form "testFromFile(file)", for all files in a given folder?
Upvotes: 1
Views: 550
Reputation: 1744
@RunWith(value = Parameterized.class)
public class JunitTest {
private String filename;
public JunitTest(String filename) {
this.filename= filename;
}
@Parameters
public static Collection<Object[]> data() {
Object[][] data = new Object[][] { { "file1.xml" }, { "file2.xml" } };
return Arrays.asList(data);
}
@Test
public void Test() {
System.out.println("Test name:" + filename);
}
}
Upvotes: 1
Reputation: 1558
Not sure, but may be these can help you. Reference1 Reference2. Hope this helps.
Upvotes: 1
Reputation: 32969
You could use Theories
where the files are @DataPoints
so you won't need to loop in your test and will allow for setup and cleanup after each file. But it will still be reported as such.
Theories also have the issue that they fail fast (quit after first failure) as your test above does. I find that this is not good practice since it can hide a situation where you have multiple bugs. I recommend using seperate tests or use the loop with an ErrorCollector
. I really wish Theories
had ErrorCollector
built in.
Upvotes: 2