Home > Spring, TestNG > Using Session/Request-Scoped SpringBeans in TestNG

Using Session/Request-Scoped SpringBeans in TestNG

Wednesday, 15. October 2008 Leave a comment Go to comments

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 :)

  1. digitaljoel
    Tuesday, 11. January 2011 at 9:04

    Great post, even at over 2 years old. Thanks for the info.

  1. Monday, 27. April 2009 at 13:46

Leave a Reply

Please log in using one of these methods to post your comment:

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


Get every new post delivered to your Inbox.

%d bloggers like this: