ApplicationContextInitializer in general can be used for some programmatic initialization of the application context. For example, registering property sources or activating profiles with the context environment.
This example demonstrates how to use ApplicationContextInitializer with Spring tests by using 'initializers' element of @ContextConfiguration.
Example
Creating a simple Spring application
@Configuration
public class AppConfig {
@Bean
@Profile("windows")
public MyService myServiceA() {
return new MyServiceA();
}
@Bean
@Profile("other")
public MyService myServiceB() {
return new MyServiceB();
}
}
public interface MyService {
public String doSomething();
}
public class MyServiceA implements MyService {
@Override
public String doSomething() {
return "in " + this.getClass().getSimpleName();
}
}
public class MyServiceB implements MyService {
@Override
public String doSomething() {
return "in " + this.getClass().getSimpleName();
}
}
Implementing the Initializer
public class MyApplicationContextInitializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext ac) {
String os = System.getProperty("os.name");
String profile = (os.toLowerCase().startsWith("windows")) ? "windows" : "other";
ConfigurableEnvironment ce = ac.getEnvironment();
ce.addActiveProfile(profile);
}
}
The JUnit test
Following test will fail if run other than Windows O.S.
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = AppConfig.class,
initializers = MyApplicationContextInitializer.class)
public class MyServiceTests {
@Autowired
private MyService dataService;
@Test
public void testDoSomething() {
String s = dataService.doSomething();
System.out.println(s);
Assert.assertEquals("in MyServiceA", s);
}
} mvn -q test -Dtest=MyServiceTests Outputd:\example-projects\spring-core-testing\application-context-initializer-in-test>mvn -q test -Dtest=MyServiceTests
------------------------------------------------------- T E S T S ------------------------------------------------------- Running com.logicbig.example.MyServiceTests in MyServiceA Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.409 sec
Results :
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
Example ProjectDependencies and Technologies Used: - spring-context 4.3.8.RELEASE: Spring Context.
- spring-test 4.3.9.RELEASE: Spring TestContext Framework.
- junit 4.12: JUnit is a unit testing framework for Java, created by Erich Gamma and Kent Beck.
- JDK 1.8
- Maven 3.3.9
|