English 中文(简体)
在Maven的JUnit测试用例中获取文件的最清洁的方法
原标题:Cleanest way to get a File in a JUnit test case from Maven

我的Maven项目B中的测试代码(它是项目A的子项目)有这样的东西:

String filePath = "src/main/webapp";
//do something with the filePath

在我从儿童(即B级)管理该项目时,上述试办案例是罚款的,但当我从父母项目A(即,在父母一级安装一个小套)时,该试办案失败,因为显然在父母一级没有被称为“母体/母/网”的双倍(然而,在儿童一级)。

我知道我可以进行一些编码以检查测试用例是否来自父/子模块,但显然我想知道其他人在遇到这个问题时都做了什么?

不,我不能使用类路径代替(出于各种无聊的原因)。

我也尝试相对路径,但测试用例开始知道得太多了。这个问题是否有解决方案?

更新(2月12日)-我在webapp文件夹下有一个web.xml,并在一个测试用例中使用该web.xml创建了一个jetty服务器。理想情况下,src/main/webapp不会放置在类路径中。它被WAR插件用于打包WAR。现在,我尝试了一个替代方案,在src/main/resource/console-webapp/WEB-INF/web.xml目录中放置我的web.xml,并修改了maven war插件中的webXml属性。这似乎解决了我的问题。然而,在输出的WAR中,我有一个web.xml和另一个冗余的web.xml(因为它在类路径中被复制)。

我曾尝试过“包裹”和“网络资源/排斥”,并用战争花板 o倒第二个网络xml,但“console-webapp”的名录却被复制(尽管是空的)。 难道有什么办法可以告诉ven战争的 p,完全无视一个 director子(即,这种 pattern的格局是什么?)

最佳回答

Maven 2 约定规定所有测试资源,包括像您尝试在测试中使用的文件,必须存储在 src/test/resources 文件夹中。如果您遵守这个约定,您将能够直接从类路径中获取您的文件。这些资源将不会包含在最终的打包文件(JAR、WAR、EAR 等)中。

当然,您可以更改目录,然后在您的pom.xml中指定新的测试资源目录:

<build>
    <testResources>
        <testResource>
            <directory>...</directory>
        </testResource>
    </testResources>
    ...

在你的问题中,你指定了你不能使用类路径。为什么?

问题回答

你们的档案是否试图进入测试级? 如果是,如何:

public class IOUtils {

  public URL getResourceAsURL(String resource) {
    ClassLoader cl = getClass().getClassLoader();
    return cl.getResource(resource);
  }


  public static InputStream getResourceAsStream(String resource) throws IOException  {
    ClassLoader cl = getClass().getClassLoader();
    InputStream in = cl.getResourceAsStream(resource);

    if (in == null) 
      throw new IOException("resource "" + resource + "" not found");

    return in;
  }
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签