Reading XML from relative path - java.io.FileNotFoundException:(系统找不到指定的路径)

Reading XML from relative path - java.io.FileNotFoundException:(The system cannot find the path specified)

我有以下方法可以检查两个 XML 文档是否匹配:

@Test
public void currentXMLShouldMatchXMLSpecification() throws Exception {

    String xml1 = convertXMLToString("/module/docs/document1.xml");
    String xml2 = convertXMLToString("/module/docs/document2.xml");

    XMLUnit.setIgnoreWhitespace(true); // ignore whitespace differences

    assertXMLEquals(xml1, xml2); 
}

将XML转换为字符串方法:

   public static String convertXMLToString(String filePath) throws IOException {

        //filename is filepath string
        BufferedReader br = new BufferedReader(new FileReader(new File(filePath)));
        String line;
        StringBuilder sb = new StringBuilder();

        while((line=br.readLine())!= null){
            sb.append(line.trim());
        }

        return  line;
    }

断言XML等于方法:

   public static void assertXMLEquals(String expectedXML, String actualXML) throws Exception {
        XMLUnit.setIgnoreWhitespace(true);
        XMLUnit.setIgnoreAttributeOrder(true);

        DetailedDiff diff = new DetailedDiff(XMLUnit.compareXML(expectedXML, actualXML));

        List<?> allDifferences = diff.getAllDifferences();
        Assert.assertEquals("Differences found: " + diff.toString(), 0, allDifferences.size());
    }

错误:

java.io.FileNotFoundException:(The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(FileInputStream.java:146)
    at java.io.FileReader.<init>(FileReader.java:72)

我是否需要将 XML 文档移动到 Resources 文件夹下?或者这是我犯的代码错误?

请注意,包含此测试的测试 class 与我尝试阅读的文档不在同一模块中。

是的,您应该将所有非java 文件移动到资源文件夹。如果您将它们放在 module/docs/ 文件夹下,那么您还应该将代码更改为如下内容:

String xml1 = convertXMLToString("module/docs/document1.xml");
String xml2 = convertXMLToString("module/docs/document2.xml");

resources 文件夹下的所有文件将自动复制到您的 classpath 根文件夹,因此 module/ 文件夹将相对于您 class 的根文件夹路径。

编辑: 当您进行测试时,您的测试文件夹有自己的 resources 文件夹,因此应该可以在那里访问文件。如果你想在那里动态复制你的文件,那么你可以通过以下方式之一进行:

  1. 将文件复制到测试的 @Before 方法中的测试输出文件夹。在您的测试中用 @Before 注释的方法,在您的单元测试 class.

  2. 中的任何测试之前 运行s
  3. 使用构建脚本(maven、gradle 等)在测试之前添加一个额外步骤 运行

我建议使用第二种方法,因为它更健壮且可配置。

对于 java 这样的单元测试,我对测试文件的建议是:

  1. 测试资源在 src/test/resources 下,然后在一个文件夹中以匹配测试包 class。
  2. 使用 commons-io 中的 IOUtils.toString(InputStream) 读入文件。
  3. 使用 Class.getResourcesAsStream(String) 引用文件本身。

因此对于 com.my.package.MyTest,我会将 XML 文件保存为 src/test/resources/com/my/package/test_document1.xml,代码可能如下所示:

try(InputStream in = MyTest.class.getResourceAsStream("test_document1.xml")) {
    return IOUtils.toString(in);
}