感谢 Javier 的建议,我能够让我的程序动态编译和运行 JUnit 测试用例。我正在使用它来运行 Selenium IDE 导出的 .java 文件。下面是我完成的例子。希望这可以帮助其他寻找类似解决方案的人。另一个说明我正在使用 Eclipse IDE 进行开发,快乐编码!
//the loc and name variables are gathered from user input
String fileloc = loc +"/"+ name + ".java";
JavaCompiler jCompiler = ToolProvider.getSystemJavaCompiler();
List<String> options = Arrays.asList("-d", "./bin/",fileloc);
int compilationResult = jCompiler.run(null, null, null,
options.toArray(new String[options.size()]));
if (compilationResult == 0){
//This is the package name exported from selenium IDE exported files
File file = new File("./bin/com/example/tests/" + name);
URL url = null;
try {
url = file.toURL();
URL[] urls = {url};
ClassLoader cl = new URLClassLoader(urls);
org.junit.runner.Result result = JUnitCore.runClasses(cl.loadClass
("com.example.tests." + name));
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
};
} catch (MalformedURLException e) {
System.out.println("Error with file location (URL)");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("Couldn't Not Find Test Class To Load");
e.printStackTrace();
}
}else{
System.out.println("Could not Find Java Source File Located in `" + fileloc + "`");
System.exit(1);
}
}