Monday, September 5, 2016

Create dynamic junit testcases

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import java.io.File;
import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {
 private static final String TEST_FOLDER = "test_folder";

 public static Test suite() {
  TestSuite suite = new TestSuite();
  suite.addTest(new MyTestSuite(new File(TEST_FOLDER)));
  return suite;
 }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import java.io.File;
import junit.framework.TestSuite;

public class MyTestSuite extends TestSuite {
 public MyTestSuite(File directory) {
  super(directory.getName());
  
  for (File file : directory.listFiles()) {
   if (file.isDirectory())
    addTest(new MyTestSuite(file));
   else
    addTest(new MyTestCase(file));
  }
 }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
import java.io.File;
import junit.framework.TestCase;

public class MyTestCase extends TestCase {
 File file;

 public MyTestCase(File file) {
     super();
     this.file = file;
     setName(file.getName());
 }
 
 @Override
 protected void runTest() throws Throwable {
     assertEquals("test.txt", file.getName());
 }

}

No comments:

Post a Comment