Search code examples
springspring-annotationsspring-test

Define spring property values in Java


I have some spring beans which wire in property values using the @Value annotation.

e.g.

@Value("${my.property}")
private String myField;

Usually the values are sourced from property files.

The test I am currently writing uses a fully annotation based configuration.

e.g.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader=AnnotationConfigContextLoader.class)
public class AcceptanceTest implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Configuration
    @ComponentScan(basePackages = {
        "my.package.one",
        "my.package.two"
    })
    static class ContextConfiguration {
        @Bean
        public MyBean getMyBean(){
            return new MyBean();
        }
    }

    @Autowired
    private AnotherBean anotherBean;

    @Test
    public void testTest(){
        assertNotNull(anotherBean);
        . . .
    }   
    . . .

I don't wish to reference an external properties file, as I want to keep everything local to the test.

Is there anyway I can specify in java, values for such properties, so that they will be wired in automatically to any beans which need them.

Any help would be appreciated.


Solution

  • As of Spring Framework 4.1, you can use the @TestPropertySource annotation to declare inlined properties for the ApplicationContext loaded for your tests like this:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration
    @TestPropertySource(properties = { "foo = bar", "magicNumber: 42" })
    public class ExampleTests { /* ... */ }
    

    Consult the Context configuration with test property sources section of the reference manual for details.


    Prior to Spring Framework 4.1, the easiest way is to configure a custom PropertySource and register it with the Spring TestContext Framework (before the ApplicationContext is loaded for your test).

    You can achieve this by implementing a custom ApplicationContextInitializer and using an org.springframework.mock.env.MockPropertySource like this:

    public class PropertySourceInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    
        public void initialize(ConfigurableApplicationContext applicationContext) {
             applicationContext.getEnvironment().getPropertySources().addFirst(
               new MockPropertySource().withProperty("foo", "bar"));
        }
    }
    

    You can then register your initializer for your test like this:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(initializers = PropertySourceInitializer.class)
    public class ExampleTests { /* ... */ }
    

    Regards,

    Sam (author of the Spring TestContext Framework)