2013-11-20 33 views
0

在单元测试中作为副作用,我正在为GUI的各个部分创建屏幕截图。 我想在编译文档时使用这些屏幕截图。将文件从单元测试保存到项目树

因此我想将它们保存到源代码树中的一个目录。

在运行junit测试时,有没有可靠的方法来获取源目录root?

如果没有,如何确保在使用eclipse和使用maven时使用cwd = project root运行单元测试?

回答

1

如果您在创建文件时没有指定路径,它会在项目根目录自动创建,您是否可以在eclipse上执行测试或使用maven进行测试。

因此,如果指定相对文件夹的文件会去那儿:

public class TestFileCreation { 

@Test 
public void testFileCreation() throws IOException { 
    File f = new File("src/main/resources/hello.txt"); 
    OutputStream ostream = new FileOutputStream(f); 
    String data = "Hello there !"; 
    ostream.write(data.getBytes()); 
    ostream.close(); 
} 

}

将创建$ PROJECT/src目录/主/资源中的文件。

希望我的回答有帮助

+0

谢谢,我已采取此方向。我正在检查目录的存在以确保我处于正确的位置。 –

0

你可以根据你的课程位置。这里建议的解决方案是使用肯定会在classpath中的类。那么你可以使用class.getResource("")。实施例

public class ResouceRoot { 

    public static String get() { 
     String s = ResouceRoot.class.getResource("").toString(); 
     if (s.startsWith("jar:")) { 
      s = s.replace("jar:", "").replaceAll("!.*", ""); 
     } else { 
      s = s.replaceAll("classes.*", "classes"); 
     } 
     File f = new File(s.replace("file:", "")); 
     return f.getParentFile().getParentFile().getAbsolutePath(); 
    } 

    public static void main(String[] args) throws IOException { 
     System.out.println(get()); 
    } 
} 

(此代码会给基dir来netbeans的项目,如果它们是从发射的netbeans或通过java -jar ...

相关问题