How to get the path of src/test/resources directory in JUnit?

前端 未结 14 1787
时光取名叫无心
时光取名叫无心 2020-11-28 01:25

I know I can load a file from src/test/resources with:

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

But how can I get the full path to th

相关标签:
14条回答
  • 2020-11-28 02:16

    Use the following to inject Hibernate with Spring in your unit tests:

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

    If you don't have the hibernate.cfg.xml present in your src/test/resources folder it will automatically fall back to the one in your src/main/resources folder.

    0 讨论(0)
  • 2020-11-28 02:18

    You don't need to mess with class loaders. In fact it's a bad habit to get into because class loader resources are not java.io.File objects when they are in a jar archive.

    Maven automatically sets the current working directory before running tests, so you can just use:

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

    resourcesDirectory.getAbsolutePath() will return the correct value if that is what you really need.

    I recommend creating a src/test/data directory if you want your tests to access data via the file system. This makes it clear what you're doing.

    0 讨论(0)
提交回复
热议问题