Skip to content

Instantly share code, notes, and snippets.

@djangofan
Last active January 11, 2016 23:48
Show Gist options
  • Save djangofan/39329fb0d65000fc8e9c to your computer and use it in GitHub Desktop.
Save djangofan/39329fb0d65000fc8e9c to your computer and use it in GitHub Desktop.
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextLoader;
/**
* This class is responsible for determining which spring context should be used.
* This allows us to support running integration tests as a unit/integration tests and via web services.
* @ContextConfiguration(value = "classpath:test-beans.xml", loader = TestContextProvider.class)
* http://www.waitingforcode.com/spring-framework/context-loader-in-spring/read
*/
class TestContextProvider implements ContextLoader, ApplicationContextAware
{
private static ApplicationContext applicationContext;
@Override
public String[] processLocations(Class<?> aClass, String... contextLocations)
{
return contextLocations;
}
/**
* Returns an existing spring context or creates a new one based on the given context locations.
* @param contextLocations the spring context to load if one does not already exist.
* @return Upon execution, if valid spring context is found, then it is returned. Otherwise a new
* one is created based on the given context locations.
*
* <br/>
* <br/>
* Use Case 1: Spring context is loaded via Tomcat, when tests are executed, they should use that context as oppose to create a new one.
* <br/>
* Use Case 2: Executing tests within maven or IDE, a new context will be returned since one isn't already available.
*/
@Override
public ApplicationContext loadContext(String... contextLocations)
{
if(AutomationTestContextProvider.getApplicationContext() == null)
{
applicationContext = new ClassPathXmlApplicationContext(contextLocations);
}
return applicationContext;
}
/**
* Called by Spring to set the application context.
* @param context the context created by Spring.
*/
public void setApplicationContext(ApplicationContext context)
{
this.applicationContext = context;
}
/**
* Return the current Spring application context.
* @return the current Spring application context.
*/
public static ApplicationContext getApplicationContext()
{
return applicationContext;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment