[英]Running JUnit tests programmatically outside of their Eclipse project
我试图从正在Eclipse中开发的应用程序运行JUnit测试,如下所示:
JUnitCore junitCore = new JUnitCore();
ClassLoader cl = Main.class.getClassLoader();
Class<?> test = cl.loadClass("test.TestCase1");
Result r = junitCore.run(test);
这样可以很好地运行,但是如果测试用例需要使用一些文件,则会收到FileNotFoundException
。 在Eclipse项目中运行相同的测试,该测试没有此类错误。 我认为这是因为我的JVM的工作目录(在user.dir
属性中定义)与Eclipse项目不同。 据我所知,我无法在运行的JVM中更改user.dir
。
我该怎么做才能改变这种行为? 我唯一的选择是使用与Eclipse项目相同的工作目录来启动新的JVM吗? 如果是这样,我该怎么做,最好不要使用Ant之类的工具?
编辑:这是一个通过Eclipse项目的测试示例,当我在项目外部以编程方式运行它时会生成FileNotFoundException
:
@Test
public void test() throws Exception {
FileInputStream fstream = new FileInputStream("test1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
assertEquals("file content", br.readLine());
}
试试这个代码
new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("filename")));
如果您的文件与java类位于同一目录中,则应将其加载。
更新资料
在这种情况下,请在运行JUnits测试时尝试指定工作目录。
-Duser.dir=somedir
尝试检索您的JUnit测试所在的当前目录,然后创建一个新文件,导航到test1.txt
String currentDirectory = new File("").getAbsolutePath();
FileInputStream fstream = new FileInputStream(currentDirectory+"\\XYZ\\test1.txt");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.