alexcuesta

My tech blog

Setup a WebApplicationContext to test Listeners with Spring

leave a comment »

I need to test a listener:

public void contextInitialized(ServletContextEvent sce) {
  ServletContext servletContext = sce.getServletContext();
  WebApplicationContext context = WebApplicationContextUtils
                                  .getRequiredWebApplicationContext(servletContext);
  Map applicationProperties = (Map) context.getBean(APPLICATION_SCOPE_PROPERTIES);	
}

It took me a while to setup the proper WebApplicationContext to test it so here it is:

@Before
public void before() {
  servletContext = new MockServletContext();		
  XmlWebApplicationContext webcontext = new XmlWebApplicationContext();
  webcontext.setConfigLocation("/testContext.xml");
  webcontext.setServletContext(servletContext);
  webcontext.refresh();
  
  servletContext.setAttribute(
    WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, 
	webcontext);
  configurer = new ApplicationConfigurerListener();
}

Written by alexcuesta

July 30, 2010 at 1:41 pm

Posted in Java

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: