【问题标题】:How do I have common file path for Windows and Linux in Junit Test Suite?如何在 Junit Test Suite 中为 Windows 和 Linux 提供通用文件路径?
【发布时间】:2017-02-04 16:16:29
【问题描述】:

我的 Junit 测试套件配置为在 Windows 和 Linux 环境中执行。我开发了两种可能的代码来实现相同的目标。我真的不确定以下代码与操作系统无关的行为。我是java新手。请提出建议。

public static void main(String[] args) {
        String directoryRootFromFile = null;
        String directoryRootFromUserDir = null;
        String propertiesPath = null;
        directoryRootFromFile = new java.io.File(".").getAbsolutePath()  + File.separatorChar + "data";
        directoryRootFromUserDir = System.getProperty("user.dir") + File.separatorChar + "data";
        propertiesPath = directoryRootFromFile + File.separatorChar + "abc.properties";
        System.out.println(propertiesPath);
        propertiesPath = directoryRootFromUserDir + File.separatorChar + "abc.properties";
        System.out.println(propertiesPath);
    }   

1st Output : C:\workspace\test\.\data\abc.properties
2nd Output : C:\workspace\test\data\abc.properties

【问题讨论】:

  • 你测试了吗?它可以在 Linux 和 Windows 上运行吗?问题是什么?
  • 您应该将文件添加到类路径并使用 Class.getResource() 加载广告
  • @Jim - 我用 Windows 进行了测试并附上了结果。第一个输出不是有效的文件路径。
  • 其实它一个有效的路径。如果你想看到它被清理干净,请Paths.get(directoryRootFromFile).normalize().toString()

标签: java junit


【解决方案1】:

使用相对路径。不要将路径操作为Strings;相反,使用PathPaths 类。使用 JUnit TemporaryFolder 类创建一个自动为您设置和拆除的测试夹具。

【讨论】:

  • 谢谢。我会考虑这个选项。
【解决方案2】:

假设以下源布局。

├── pom.xml
└── src
    ├── main
    │   ├── java
    │   └── resources
    └── test
        ├── java
        │   └── test
        │       └── FileTest.java
        └── resources
            └── data
                └── abc.properties

其中abc.properties有以下内容。

foo=foo property value
bar=bar property value

以下测试通过。

@Test
public void test() throws FileNotFoundException, IOException {

    String testRoot = this.getClass().getResource("/").getFile();

    Path path = Paths.get(testRoot, "data", "abc.properties");

    File file = new File(path.toUri());

    Properties prop = new Properties();
    prop.load(new FileInputStream(file));

    assertEquals("foo property value", prop.get("foo"));
    assertEquals("bar property value", prop.get("bar"));

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    • 2017-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多