简体   繁体   中英

Load Spring Boot file system resource / config from project root directory instead of module's while running tests

I've got a Spring Boot muli-module project with a config file in its root:

project-root
|
\-- config
|   \-- file.yaml
|
\-- module1
|   \-- pom.xml
|
\-- module2
|   \-- src
|   |   \-- main
|   |   |   \-- ...
|   |   \-- test
|   |       \-- java
|   |           \-- test.java
|   |
|   \-- pom.xml
|
\-- module3
|   \-- pom.xml
...
|
\-- moduleN
|   \-- pom.xml
|
\-- pom.xml

Some classes in the modules (for example project-root/module2/src/main/**.java ) load the file.yaml using

new FileSystemResource("config/file.yaml");

in their constructors successfully, but when I run test.java , which contains:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Test.class, webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class Test {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    public void test() {
        String body = this.restTemplate.getForObject("/", String.class);
        assertThat(body)...
        ...
    }

    ...
}

and the resource-loading code gets covered, I get a FileNotFoundException saying the file.yaml is expected in project-root/module2/config (instead of project-root/config ). Why?

You haven't said how you're running your tests, but when you run them with Maven it changes the working directory to the directory of the module which is being built and tested. In Maven terminology, this is referred to as the basedir This is documented here . If you're running the tests in your IDE, it, presumably, mimics Maven's behaviour for consistency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM