我知道我可以从src/test/resources加载一个文件:

getClass().getResource("somefile").getFile()

但是我怎么能得到src/test/resources目录的完整路径,即我不想加载一个文件,我只想知道目录的路径?


当前回答

在Spring中,你可以这样使用:

import org.springframework.core.io.ClassPathResource;

// Don't worry when use a not existed directory or a empty directory
// It can be used in @before
String dir = new ClassPathResource(".").getFile().getAbsolutePath()+"/"+"Your Path";

其他回答

在一般情况下,不能将资源文件夹中的文件用于测试。原因是资源文件夹中的资源文件存储在jar中。它们在文件系统中没有真正的路径。

最简单的解决方法是:

将文件从资源复制到临时文件夹,并获取该临时文件的路径。 使用临时路径执行测试。 删除临时文件。

来自JUnit的TemporaryFolder可以用来创建临时文件,并在测试完成后删除它。番石榴库中的类用于从资源文件夹中复制文件。

请注意,如果我们使用resources文件夹中的子文件夹,就像good文件夹一样,我们不必在资源路径中添加前导/。

public class SomeTest {

    @Rule
    public TemporaryFolder tmpFolder = new TemporaryFolder();


    @Test
    public void doSomethinge() throws IOException {
        File file = createTmpFileFromResource(tmpFolder, "file.txt");
        File goodFile = createTmpFileFromResource(tmpFolder, "good/file.txt");

        // do testing here
    }

    private static File createTmpFileFromResource(TemporaryFolder folder,
                                                  String classLoaderResource) throws IOException {
        URL resource = Resources.getResource(classLoaderResource);

        File tmpFile = folder.newFile();
        Resources.asByteSource(resource).copyTo(Files.asByteSink(tmpFile));
        return tmpFile;
    }

}

尝试使用ClassLoader类:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("somefile").getFile());
System.out.println(file.getAbsolutePath());

ClassLoader负责装入类。每个类都有一个对ClassLoader的引用。这段代码从资源目录返回一个File。对其调用getAbsolutePath()将返回其绝对路径。

Javadoc for ClassLoader: http://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html

你不需要干扰类加载器。事实上,这是一个不好的习惯,因为当类装入器资源在jar存档中时,它们不是java.io.File对象。

Maven在运行测试之前自动设置当前工作目录,因此您可以使用:

    File resourcesDirectory = new File("src/test/resources");

getabsolutepath()将返回正确的值,如果这是你真正需要的。

如果您希望您的测试通过文件系统访问数据,我建议创建一个src/test/data目录。这让你清楚地知道你在做什么。

在Spring中,你可以这样使用:

import org.springframework.core.io.ClassPathResource;

// Don't worry when use a not existed directory or a empty directory
// It can be used in @before
String dir = new ClassPathResource(".").getFile().getAbsolutePath()+"/"+"Your Path";

使用以下命令在单元测试中注入Hibernate和Spring:

@Bean
public LocalSessionFactoryBean getLocalSessionFactoryBean() {
    LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
    localSessionFactoryBean.setConfigLocation(new ClassPathResource("hibernate.cfg.xml"));
    localSessionFactoryBean.setPackagesToScan("com.example.yourpackage.model");
    return localSessionFactoryBean;
}

如果你的src/test/resources文件夹中没有hibernate.cfg.xml,它会自动回到src/main/resources文件夹中。