Reload or refresh a Spring application context inside a test method?

By design, programmatic refreshing of an ApplicationContext is not explicitly supported by the Spring TestContext Framework. Furthermore, it is not intended that a test method refresh a context.

Thus I would recommend that you reassess your need for a refresh and consider alternatives like placing test methods that require a different set of active profiles in a dedicated test class.

In summary, @ActiveProfiles supports declarative configuration (via value and profiles attributes) and programmatic configuration (via the resolver attribute) of the active profiles for tests, but only at the test class level (not at the method level). Another option is to implement an ApplicationContextInitializer and configure that via @ContextConfiguration(initializers=...).

The only other way to affect the ApplicationContext before it is refreshed is to implement a SmartContextLoader or extend one of the provided classes and configure it via @ContextConfiguration(loader=...). For example, AbstractGenericContextLoader.customizeContext() allows one to “customize the GenericApplicationContext created by the loader after bean definitions have been loaded into the context but before the context is refreshed.”

Best regards,

Sam (author of the Spring TestContext Framework)

Leave a Comment