I get a -1
value returned when trying to get the server.port
property from application.yml
in a test context.
I do black box testing of a Spring-bot app. Here's a test case:
@SpringApplicationConfiguration(TestConfiguration.class)
public class StartupTest extends AbstractTestNGSpringContextTests implements EnvironmentAware {
private static Logger logger = LoggerFactory.getLogger(StartupTest.class);
@Value("${server.port}")
private String port;
@Value("${project.name}")
private String name;
private RelaxedPropertyResolver propertyResolver;
@Override
public void setEnvironment(Environment environment) {
this.propertyResolver = new RelaxedPropertyResolver(environment);
}
@Test
public void isAppUpAndRunning() {
logger.debug("port: " + port);
logger.debug("name: " + name);
logger.debug("value for project.name: " + propertyResolver.getProperty("project.name"));
logger.debug("value for server.port: " + propertyResolver.getProperty("server.port"));
logger.debug("value for server.servlet-path: " + propertyResolver.getProperty("server.servlet-path"));
}
}
NB: TestConfiguration.class
contains nothing but @Configuration
Output:
[DEBUG] com.project.StartupTest - Running with Spring Boot v1.3.3.RELEASE, Spring v4.2.5.RELEASE
[INFO] com.project.StartupTest - The following profiles are active: test
[INFO] com.project.StartupTest - Started StartupTest in 4.698 seconds (JVM running for 7.761)
[DEBUG] com.project.StartupTest - port: ${server.port}
[DEBUG] com.project.StartupTest - name: ${project.name}
[DEBUG] com.project.StartupTest - value for project.name: MyProject
[DEBUG] com.project.StartupTest - value for server.port: -1
[DEBUG] com.project.StartupTest - value for server.servlet-path: /
So there's actually 2 questions here:
- why can't I get the properties injected with the
@Value
annotation? - why can I get all
application.yml
properties with aPropertyResolver
butserver.port
?
What I need ultimately is a convenient way to access all the application.yml
properties in a 'classic' test (i.e. not a Spring integration test as I want to test the application as it is at runtime). I've tried using
@ContextConfiguration(classes = TestConfiguration.class, initializers = ConfigFileApplicationContextInitializer.class)
as well, but the problem remains the same.