我正在运行一些junit测试,在我的项目的main/java部分中,我有一个类需要从资源文件夹中读取xslt样式表,该文件夹位于子文件夹
resources/xslt/mystylesheet.xsl
中。我做了很多谷歌搜索,发现了很多像this这样的东西。
我的班级中有这个验证方法(不是单元测试)
private void validateInput(NeptuneXmlPipelineElement input) throws Exception {
ClassLoader classLoader = this.getClass().getClassLoader();
File f = new File(classLoader.getResource(stylesheetPath).getFile());
// other things I have tried....
// InputStream is = getClass().getResourceAsStream(stylesheetPath);
// InputStream is = MyAppClass.class.getClassLoader().getResourceAsStream(stylesheetPath);
// I tried this to test some other files in the resources dir, but all were not found
// InputStream is = getClass().getResourceAsStream("log4j2.xml");
if (!f.exists()) {
String errorMsg = "unable to locate xslt stylesheet " + stylesheetPath;
input.getConversionResult().addMessage(errorMsg);
throw new FileNotFoundException(errorMsg);
}
}
当我查看项目目标/类文件夹时,我看到了这个:
└───xslt
│ mystylesheet.xsl
问题是……这一切过去都有效。我对项目做了很多更改,当我开始重新运行一系列测试时,结果失败了。
是不是因为我在测试环境运行时找不到文件?
这是我的测试片段:
@Test
public void testPipelineWorkflow() {
String filePath = "src/test/resources/xml/mockup1_with_doctype.xml";
String stylesheetPath = "xslt/mystylesheet.xsl";
由于 src/test 文件夹未导出到目标目录,因此在使用 src/test/resources 目录中的文件时,我只使用如上所示的相对路径...但是由于样式表导出到目标目录,因此加载作为资源应该有效。
我创建了一个带有 main 方法的测试器类。我想看看错误是否是由代码执行源自测试用例这一事实引起的(不是......)
无论如何,我的测试人员有这个方法:
public void testResource() {
String xsltPath = "xslt/mystylesheet.xsl";
InputStream is = getClass().getClassLoader().getResourceAsStream(xsltPath);
URL url = getClass().getClassLoader().getResource(xsltPath);
System.out.println("is input stream null? " + is);
System.out.println("is url null? " + url);
}
上面的代码有同样的错误,找不到样式表...但是当我更改
xslt/mystylesheet.xsl' to just
xslt' 时,我没有得到空值...这表明它可以看到文件夹,但看不到里面的文件。
我尝试按照 maven 文档在 pom 中添加“/resources/resource/include/directory”,但是当我这样做时,资源中的文件/文件夹未在构建中导出。
知道我做错了什么吗?
谢谢!!
我能够通过将以下内容添加到我的 pom 来解决该问题:
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/resources/xslt</directory>
</resource>
</resources>
我还有一个遗留问题,即目录结构未保留在目标/类中...所有文件都被复制到主目录。现在这并不重要,所以暂时接受它。