更改位于src / test / resources中的属性文件

时间:2015-03-16 20:11:42

标签: java apache maven junit4

我正在探索Apache Common Configuration,并希望进行一项测试,只需从测试中读取/写入位于src / test / resources中的xml文件的属性。 到目前为止,我正在阅读没有问题,但不能写任何东西到这个文件。 如果我将文件的位置从scr / test / resources更改为文件系统中的另一个位置(例如:c:/ test),一切正常。 你能帮我解决这个问题吗?

修改

这是我到目前为止所尝试的内容:

    @Test
public void test() throws ConfigurationException {
    //First with data.xml located in src/test/resources
    XMLConfiguration config = new XMLConfiguration("data.xml");

    List<Object> rows = config.getList("user.username");
    System.out.println(rows);

    //This is not working
    config.setProperty("user.username", "FromTest");
    config.save();      

    // Second with data.xml in different location
    XMLConfiguration config = new XMLConfiguration("c:/temp/data.xml");

    List<Object> rows = config.getList("user.username");
    System.out.println(rows);   

    //This works
    config.setProperty("user.username", "FromTest");
    config.save();
}

感谢。

1 个答案:

答案 0 :(得分:1)

好吧,你没有提供关于运行上下文的很多见解,但是从 src / test / resources 路径,我猜你使用Maven。 如果这是真的,那就是这样:

  1. Maven将资源复制到 target / test-classes
  2. 测试方法对复制的资源进行操作,因此 target / test-classes / data.xml
  3. 如果您检查此文件,它可以正常工作。我只是查看了源文件,而不是实际从代码中读取的文件。

    与第二个测试 c:/temp/data.xml 的区别在于前者是相对路径,而后者是绝对路径,而不是Maven的范围。