Standard Spring Boot locations
If you want spring-boot's application.properties
to be loaded, you should launch the unit test with Spring Boot (using @SpringApplicationConfiguration
):
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { AppConfig.class })
public class FooServiceTest {
@Test
public void test...
}
The application.yml
should be under /config
or root
in the classpath.
See Spring Doc:
SpringApplication will load properties from application.properties
files in the following locations and add them to the Spring
Environment:
- A /config subdirectory of the current directory.
- The current directory
- A classpath /config package
- The classpath root
Specify additional locations (exemple when executed from unit tests)
Normally, you could have used PropertySource
, however even though it allows to load configuration files from other locations, it will not work for injected (@Value
) properties.
You may however specify the spring.config.location
environment variable in a static bloc:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = { AppConfig.class })
public class FooServiceTest {
static {
//if the file is NOT in the classpath
System.setProperty("spring.config.location", "file:///path/to/application.yml");
//if the file is in the classpath
//System.setProperty("spring.config.location", "classpath:/path/in/classpath/application.yml");
}
@Test
public void test...
}
Run tests from Gradle
According to this you may do this:
$ gradle test -Dspring.config.location=file:///path/to/application.yaml
Or
$ SPRING_CONFIG_LOCATION=file:///path/to/application.yaml gradle test
Or add a task to define the systemProperty:
task extconfig {
run { systemProperty "spring.config.location", "file:///path/to/application.yaml" }
}
test.mustRunAfter extconfig