在Eclipse项目之外以编程方式运行JUnit测试

时间:2012-02-16 10:00:12

标签: java eclipse junit

我正在尝试从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());
}

2 个答案:

答案 0 :(得分:0)

试试此代码

new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("filename")));

如果您的文件与java类位于同一目录中,则应加载该文件。

<强>更新

在这种情况下,尝试在运行JUnits测试时指定工作目录

-Duser.dir=somedir

答案 1 :(得分:0)

尝试检索JUnit Test所在的当前目录,然后创建一个导航到test1.txt的新文件

String currentDirectory = new File("").getAbsolutePath();

FileInputStream fstream = new FileInputStream(currentDirectory+"\\XYZ\\test1.txt");