繁体   English   中英

在Junit Test Suite中如何为Windows和Linux设置通用文件路径?

[英]How do I have common file path for Windows and Linux in Junit Test Suite?

我的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

使用相对路径。 不要将路径作为字符串处理; 而是使用Path和Paths类。 使用JUnit TemporaryFolder类创建一个自动为您安装和拆卸的测试装置。

假设以下源代码布局。

├── 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"));

}

暂无
暂无

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

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