Luc*_*uke 7 java dbunit java-ee maven
我正在使用maven和标准目录布局.所以我在src/test/resources文件夹中添加了一个testdata.xml文件,我还将其添加为:
.addAsWebInfResource("testdata.xml", "testdata.xml")
Run Code Online (Sandbox Code Playgroud)
在部署方法中,我已经确认它在那里.这将使文件出现/WEB-INF/testdata.xml.现在我需要在我的代码中引用这个文件,我尝试了几个不同的getClass().getResourceAsStream(...)并且一次又一次地失败,所以我现在需要一些建议.
我需要它用于我的DBUnit集成测试.这不可能吗?
Gle*_*est 19
选项A)使用ServletContext.getResourceXXX()
你应该有一个Aquillarian MockHttpSession和一个MockServletContext.例如:
@Test
public void myTest()
{
HttpSession session = new MockHttpSession(new MockServletContext());
ServletLifecycle.beginSession(session);
..testCode..
// You can obtain a ServletContext (will actually be a MockServletContext
// implementation):
ServletContext sc = session.getServletContext();
URL url = sc.getResource("/WEB-INF/testdata.xml")
Path resPath = new Path(url);
File resFile = new File(url);
FileReader resRdr = new FileReader(resFile);
etc...
..testCode..
ServletLifecycle.endSession(session);
}
Run Code Online (Sandbox Code Playgroud)
您可以在以下位置创建资源文件和子目录:
在所有情况下,可以通过以下方式访问资源:
URL url = sc.getResource("/<path from web doc root>/<resourceFileName>");
OR
InputStream resIS = sc.getResourceAsStream("/<path from web doc root>/<resourceFileName>");
Run Code Online (Sandbox Code Playgroud)
>
这些将打包到WAR文件中,并可能会展开到已部署的应用服务器上的目录中,或者它们可能保留在应用服务器上的WAR文件中.无论哪种方式 - 访问资源的相同行为:使用ServletContext.getResourceXXX().
注意,作为一般原则,(5)顶级WEB-INF目录本身旨在供服务器使用.将这些网络资源直接放在这里或直接在这里创建自己的目录是"礼貌的".相反,最好使用上面的(2).
选项B):使用Class.getResourceXXX()
首先将资源从WEB-INF文件夹移到WEB-INF/classes(或在jar-WEB/INF/lib/*.jar中).
如果您的测试类是:
你的资源文件是
使用相对文件位置访问文件,通过Java ClassLoader - 找到相对于Classpath的文件夹/ Jars:
java.net.URL resFileURL = MyTest.class.getResource("resources/testdata.xml");
File resFile = new File(fileURL);
OR
InputStream resFileIS =
MyTedy.class.getResourceAsStream("resources/testdata.xml");
Run Code Online (Sandbox Code Playgroud)
访问文件使用完全类似于Package的资格,使用Java ClassLoader - 查找相对于Classpath的文件夹/ Jars:
java.net.URL resFileURL = MyTest.class.getResource("/com/abc/pkg/test/resources/testdata.xml");
File resFile = new File(fileURL);
OR
InputStream resFileIS =
MyTest.class.getResourceAsStream("/com/abc/pkg/test/resources/testdata.xml");
OR
java.net.URL resFileURL = MyTest.class.getClassLoader().getResource("com/abc/pkg/test/resources/testdata.xml");
File resFile = new File(fileURL);
OR
InputStream resFileIS =
MyTest.class.getClassLoader().getResourceAsStream("com/abc/pkg/test/resources/testdata.xml");
Run Code Online (Sandbox Code Playgroud)
希望指甲吧!@B)
WEB-INF通过以下三种方法访问文件ServletContext:
getResource("/WEB-INF/testdata.xml") 给你一个URLgetResourceAsStream 给你输入流getRealPath 为您提供相关文件在磁盘上的路径。前两个应该总是可以工作,如果资源路径和磁盘上的文件之间没有直接对应关系,例如,如果您的Web应用程序是直接从WAR文件而不是从解压缩的目录结构运行的,则前三个可能会失败。