Using Session/Request-Scoped SpringBeans in TestNG

Today i will show you how to use spring-beans (especially session-scoped respectively request-scoped) in Unittests.

First of all … its easy to use a singleton bean (no scope) in a unit-test, load the ClassPathXmlApplicationContext with configLocations, use getBean(“name”) and then use the returned objects.

But if you want use a enhanced (J2EE) spring-configuration in your unit-test you have to use the XmlWebApplicationContext.

Lets use a simple example! Imagine you have different context-files, e.g. spring-beans-application.xml:

  <bean id="Foobar1" class="de.ahoehma.test.Foobar" scope="request"/>
  <bean id="Foobar2" class="de.ahoehma.test.Foobar" scope="session"/>
  <bean id="Foobar3" class="de.ahoehma.test.Foobar" />

Then you have your unit-test:

public class SpringBeansTestNg {

  // XXX we have to define all spring-context-files - later this could be done via test-ng-provider or
  //     via spring with "spring-beans-*.xml" (i try it but it doesnt work)
  private final String[] contextLocations = new String[]{

  private ApplicationContext applicationContext;

  private void loadApplicationContext() {
    final XmlWebApplicationContext xmlApplicationContext = new XmlWebApplicationContext();
    final MockServletContext servletContext = new MockServletContext("");
    final RequestContextListener requestContextListener = new RequestContextListener();
    final MockHttpServletRequest request = new MockHttpServletRequest(servletContext);
    final ServletRequestEvent requestEvent = new ServletRequestEvent(servletContext, request);
    applicationContext = xmlApplicationContext;

   * @return request scoped bean
  private Foobar getFoobar1() {
    return (Foobar) applicationContext.getBean("Foobar1"); //$NON-NLS-1$

   * @return session scoped bean
  private Foobar getFoobar2() {
    return (Foobar) applicationContext.getBean("Foobar2"); //$NON-NLS-1$

   * @return singleton bean
  private Foobar getFoobar3() {
    return (Foobar) applicationContext.getBean("Foobar3"); //$NON-NLS-1$

The magic happend in the loadApplicationContext.

Try it :)