on ‎2019 Apr 04 8:35 PM
I'm putting together a unit test and trying to get a smallish chunk of the Spring context to confirm DI wiring is all good with annotation-driven config and do some testing.
For some reason I can't get @Value("${my.property}") injection to work. The expression below is working ('defaultValue' is the result). I've tried setting a @PropertySource on my unit test to no avail in different ways.
class Banana {
public Banana(@Value("${my.property:defaultValue}") final String myProperty) {
// do stuff
}
}
Has anyone had any luck applying this approach for getting their properties in this way?
Request clarification before answering.
Thanks for the replies - it turns out it's somewhat of a Spring framework issue when you use the "${foo}" placeholders.
You have to have a PropertySourcesPlaceholderConfigurer bean or it won't resolve the expressions to be used via injection for you despite having those properties on the classpath. The key items from below is the addition of WSClientIntegrationTest.Config.class into the ContextConfiguration and the simple bean inside the test class. Naturally this is best placed in a more higher level base class of sorts for a test context config.
If this helps someone in the future, the general idea is:
@RunWith(SpringRunner.class)
@ContextConfiguration(
classes = {WSClientIntegrationTest.Config.class, WSClient.class, WSMarshaller.class, WSMessageSender.class}
)
@TestPropertySource
public class WSClientIntegrationTest {
@Configuration
static class Config {
@Bean
public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
return new PropertySourcesPlaceholderConfigurer();
}
} // etc
}
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You can use https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/context/ContextConfi... (here is a good example of usage https://stackoverflow.com/a/41964308)
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
Justin, Did you put "my.property" and its corresponding value in your local.properties?
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.
You must be a registered user to add a comment. If you've already registered, sign in. Otherwise, register and sign in.