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

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

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


当前回答

我有一个使用JUnit 4.12和Java8的Maven3项目。 为了获得src/test/resources下名为myxml.xml的文件的路径,我在测试用例中这样做:

@Test
public void testApp()
{
    File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
    System.out.println(inputXmlFile.getAbsolutePath());
    ...
}

使用IntelliJ IDE在Ubuntu 14.04上测试。 参考这里。

Note

前置/符号是必要的,因为Class.getResource(String)不一定会显示整个文件路径(缺失)以及FileNotFoundException。

其他回答

哇,正确答案还不在这里!

MyClass.class.getResource("/somefile");
MyClass.class.getResourceAsStream("/somefile");

https://javachannel.org/posts/how-to-access-static-resources/

使用以下命令在单元测试中注入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文件夹中。

我将简单地使用Java 7中的Path

Path resourceDirectory = Paths.get("src","test","resources");

干净利落!

我有一个使用JUnit 4.12和Java8的Maven3项目。 为了获得src/test/resources下名为myxml.xml的文件的路径,我在测试用例中这样做:

@Test
public void testApp()
{
    File inputXmlFile = new File(this.getClass().getResource("/myxml.xml").getFile());
    System.out.println(inputXmlFile.getAbsolutePath());
    ...
}

使用IntelliJ IDE在Ubuntu 14.04上测试。 参考这里。

Note

前置/符号是必要的,因为Class.getResource(String)不一定会显示整个文件路径(缺失)以及FileNotFoundException。

使用Spring,你可以很容易地从资源文件夹(main/resources或test/resources)中读取:

例如,创建一个文件test/resources/subfolder/sample.json

@Test
public void testReadFile() {
    String json = this.readFile("classpath:subfolder/sample.json");
    System.out.println(json);
}

public String readFile(String path) {
    try {
        File file = ResourceUtils.getFile(path);
        return new String(Files.readAllBytes(file.toPath()));
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}