简体   繁体   English

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

[英]Running JUnit tests programmatically outside of their Eclipse project

I am trying to run JUnit tests from an application that is being developed in Eclipse, like so: 我试图从正在Eclipse中开发的应用程序运行JUnit测试,如下所示:

JUnitCore junitCore = new JUnitCore();
ClassLoader cl = Main.class.getClassLoader();
Class<?> test = cl.loadClass("test.TestCase1");
Result r = junitCore.run(test);

This runs fine, but if the test case needs to use some files, I get a FileNotFoundException . 这样可以很好地运行,但是如果测试用例需要使用一些文件,则会收到FileNotFoundException Running the same test in the Eclipse project, the test has no such error. 在Eclipse项目中运行相同的测试,该测试没有此类错误。 I think this is because my JVM's working directory (defined in the user.dir property) is not the same as the Eclipse project. 我认为这是因为我的JVM的工作目录(在user.dir属性中定义)与Eclipse项目不同。 As far as I know, I cannot change the user.dir in a running JVM. 据我所知,我无法在运行的JVM中更改user.dir

What can I do to change this behavior? 我该怎么做才能改变这种行为? Is my only option to fire a new JVM with the same working directory as the Eclipse project? 我唯一的选择是使用与Eclipse项目相同的工作目录来启动新的JVM吗? If so, how can I do that, preferably without using tools like Ant? 如果是这样,我该怎么做,最好不要使用Ant之类的工具?

edit: Here is an example of a test that passes in the Eclipse project, and generates a FileNotFoundException when I run it programmatically outside of the project: 编辑:这是一个通过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());
}

Try this code 试试这个代码

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

If your file is in the same directory as java class it should be loaded. 如果您的文件与java类位于同一目录中,则应将其加载。

Update 更新资料

In this case, try to specify working directory when you run your JUnits tests 在这种情况下,请在运行JUnits测试时尝试指定工作目录。

-Duser.dir=somedir

Try retrieving the current Directory your JUnit Test is in and then create a new File navigating to the test1.txt 尝试检索您的JUnit测试所在的当前目录,然后创建一个新文件,导航到test1.txt

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM