Peterdk
Peterdk

Reputation: 16005

Junit create tests based on dynamic data

I need to create a testsuite, with subsuites containing tests that check data for me (using a java library). The goal of it is to test if the library works ok. Think of it like a virus scanner definitions check. I have experience with the old Junit/Nunit, and expected it to be quite easy. However, it turns out it is not with Junit4.

I have the following filesystem layout:

typename(dir)
    - file1
    - file2
typename(dir)
    - file1
    - file2
    - file3
etc.

I need to run a unittest that tests each file, and lives in a "typename" testsuite. The idea is to process the filesystem and then generate the testcases and suites dynamically:

for (File typeNameDir: typenameDirs)
{
  TestSuite typenameSuite= new TestSuite();
  typenameSuite.setName(typename);
  for (File file: filesInThisDir)
  {
     typenameSuite.addTest(new FileTest(File));
  }
}

Problem now is that addTest expect a class that implements Test, but that is an interface of the framework and not usable, because of the low level methods it needs to have implemented. I also tried to extend TestCase but this also doesn't work: I need to set the testname there manually and it still doesn't run normally. Also it is discouraged to extends the junit.framework classes.

So, it looks like I need to use Parameterized option, but that doesn't allow me to input dynamically generated data... So what should I do?

I am thinking of just moving to Junit 3.

Upvotes: 0

Views: 2232

Answers (1)

Yugang Zhou
Yugang Zhou

Reputation: 7283

You may have a look at this post. The author describe a solution to generate test case at runtime.

And just for curiosity, why @Parameterized doesn't allow you to input dynamically generated data? It doesn't work like this?

@Parameters
public static Collection<Object[]> data() {
          List<Object[]> data = new ArrayList<Object[]>();
          //load files
          for (File file: filesInThisDir) {
               data.add(file);
          }

          return data;
}

Upvotes: 1

Related Questions