首页 > 解决方案 > 如何在 selenium java 中找到当前项目的根目录

问题描述

我尝试使用以下代码查找当前项目的根目录,但它并没有准确地给我项目目录路径,而是给了我用户目录路径,谷歌搜索了这个并没有找到合适的解决方案。

如果你能在这方面帮助我,那将非常有帮助。

以下是我尝试过的代码:

下面代码的目的是将图像保存到当前项目路径中,当我使用下面的代码时,它不一定保存在项目路径中。

有什么建议么?

FileUtils.copyFile(scrFile, new File(
System.getProperty("user.dir") + "/test-output/ScreenshotsTC/" + "screenshots" + currentDate + ".png"));
System.out.println("File name is: " + testname + currentDate + ".png");

标签: javaselenium-webdriver

解决方案


尝试这个:

public String getPathFromWhereApplicationIsRunning() throws Exception {
    try {
        return new File(".").getCanonicalPath();
    } catch (IOException ex) {
        throw new Exception("Failed to get the absolute path of the process.",ex);
    }
}

我多次将此方法用于独立目的(jar、maven、ant、eclipse、netbeans 等)

如果您将在服务器(war、tomcat、widfly、spring-boot 等)上运行 selenium 代码,这将不起作用。在这种情况下,它将返回:

  • tomcat:bin文件夹
  • spring-boot:启动的路径java -jar ...

建议

为屏幕截图或任何其他文件位置使用环境变量。这将适用于任何阶段:

  • 开发人员笔记本电脑/个人电脑
  • 测试/登台/生产本地或云
System.getenv("SCREENSHOT_FOLDER") + "/test-output/ScreenshotsTC/" + "screenshots" + currentDate + ".png"));

最后只需在执行前导出变量:

#linux/mac
export SCREENSHOT_FOLDER=/foo/bar/
#windows
SET SCREENSHOT_FOLDER=/foo/bar/

推荐阅读