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.
JUnit 3
JUnit 4
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:
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:Here's a sample class.
Also check this example
You could consider using JUnitParams library, so you would have a few more (cleaner) options:
You can see more samples of usage here.
In addition about JUnitParams, why writting parameterized tests with it is easier and more readable:
Should be possible in JUnit 3 by inheriting from
TestSuite
and overriding thetests()
method to list the files and for each return an instance of a subclass ofTestCase
that takes the filename as constructor parameter and has a test method that tests the file given in the constructor.In JUnit 4 it might be even easier.
I had a similar problem and ended up writing a simple JUnit 4 runner that allows med to dynamically generate tests.
https://github.com/kimble/junit-test-factory
If TestNG is an option, you could use Parameters with DataProviders.
Each individual file's test will have its result shown in the text-based report or Eclipse's TestNG plugin UI. The number of total tests run will count each of your files individually.
This behavior differs from JUnit Theories, in which all results are lumped under one "theory" entry and only count as 1 test. If you want separate result reporting in JUnit, you can try Parameterized Tests.
Test and inputs
Example output