import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import junit.extensions.TestSetup;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* @author Noman Naeem
*/
public class DynamicTestcase extends TestCase {
private final static String dataPath = System.getProperty("test.data.dir");
private ConfigData configData = null;
public DynamicTestcase(String name, ConfigData configData) {
super(name);
this.configData = configData;
}
public static Test suite() throws Exception {
TestSuite suite = new TestSuite(DynamicTestcase.class.getName());
// loads the test Config
List configsData = testConfigs(new File(dataPath));
// create test cases for the test suite
for (int i = 0; i < configsData.size(); i++) {
ConfigData configData = configsData.get(i);
String testName = "test" + DynamicTestcase.class.getSimpleName()
+ configData.getName();
suite.addTest(new DynamicTestcase(testName, configData));
}
// create test setup for the test suite
TestSetup setup = new TestSetup(suite) {
/**
* Setup paths called once during life cycle of the test suite
*/
protected void setUp() throws Exception {
// TODO: write the setup code here
}
/**
* Cleanup and called once during life cycle of the test suite
*/
protected void tearDown() throws Exception {
// TODO: write the teardown code here
}
};
return setup;
}
/**
* Execute the test as configured for each test case
*
* @throws Throwable
* @see junit.framework.TestCase#runTest()
*/
protected void runTest() throws Throwable {
if (configData == null)
throw new Exception("Cannot run with null config");
//TODO: Write code here to process config for the given test case
assertTrue(true);
}
/***************************************************************************
* Loads configs from the given input dir
*
* @param path
* The path to create the configs for
* @return List configs to run the test cases on
*/
private static List testConfigs(File path)
throws FileNotFoundException {
File[] inputFiles = null;
List configs = new ArrayList();
inputFiles = path.listFiles();
for (int i = 0; i < inputFiles.length; i++) {
if (!inputFiles[i].isDirectory()) {
// construct file name
configs.add(new ConfigData(inputFiles[i]));
}
}
return configs;
}
private static class ConfigData {
private File inputFile;
public ConfigData(File inputFile) {
this.inputFile = inputFile;
}
public File getInputFile() {
return inputFile;
}
/**
* Extracts simple file name
*
* @return The file name excluding the extension
*/
public String getName() {
String name = null;
int index = inputFile.getName().lastIndexOf('.');
if (index != -1) {
name = inputFile.getName().substring(0, index);
} else {
name = inputFile.getName();
}
return name;
}
}
}
Monday, January 18, 2010
How to create JUnit test cases dynamically
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment