且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Maven的JUnit测试用例中获取文件的最干净方法

更新时间:2023-11-19 23:08:58

Maven 2约定规定,所有测试资源(包括文件,例如您尝试在测试中使用的文件)必须存储在src/test/resources中文件夹.如果遵守此约定,则可以直接从类路径中获取文件.这些资源将包含在最终包装中(JAR,WAR,EAR ...).

The Maven 2 conventions state that all test resources, including files such as the one you are trying to use in your test, must be stored in the src/test/resources folder. If you respect this convention, you will be able to get your file from the classpath directly. These resources will not be included in the final packaging (JAR, WAR, EAR...).

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

Of course, you can change the directory and then specify the new test resources directory in your pom.xml:

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

在您的问题中,您指定不能使用类路径.为什么这样?

In your question, you specified that you can't use the classpath. Why so?