gradle - SpringBoot - @Value is not working during JUnit Test for custom spring config location -
@value not working during junit test when application.yml in location.
fooservicetest
@runwith(springjunit4classrunner.class) @contextconfiguration(classes = { appconfig.class }) public class fooservicetest {
emailservice in other module
public class emailservice { @value("${aws.credentials.accesskey}") private string accesskey;
application.yml
aws: credentials: accesskey: xxxxxxxx secretkey: zxxxxxxxxx
but got:
could not resolve placeholder 'aws.credentials.accesskey' in string value "${aws.credentials.accesskey}"
even added
-dspring_config_location=/home/foo/other/location/config/
standard spring boot locations
if want spring-boot's application.properties
loaded, should launch unit test spring boot (using @springapplicationconfiguration
):
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = { appconfig.class }) public class fooservicetest { @test public void test... }
the application.yml
should under /config
or root
in classpath.
see spring doc:
springapplication load properties application.properties files in following locations , add them spring environment:
- a /config subdirectory of current directory.
- the current directory
- a classpath /config package
- the classpath root
specify additional locations (exemple when executed unit tests)
normally, have used propertysource
, though allows load configuration files other locations, not work injected (@value
) properties.
you may specify spring.config.location
environment variable in static bloc:
@runwith(springjunit4classrunner.class) @springapplicationconfiguration(classes = { appconfig.class }) public class fooservicetest { static { //if file not in classpath system.setproperty("spring.config.location", "file:///path/to/application.yml"); //if file in classpath //system.setproperty("spring.config.location", "classpath:/path/in/classpath/application.yml"); } @test public void test... }
run tests gradle
according this may this:
$ gradle test -dspring.config.location=file:///path/to/application.yaml
or
$ spring_config_location=file:///path/to/application.yaml gradle test
or add task define systemproperty:
task extconfig { run { systemproperty "spring.config.location", "file:///path/to/application.yaml" } } test.mustrunafter extconfig
Comments
Post a Comment