Home » Java » Enterprise Java » Testing Spring “session” scope

About Biju Kunjummen

Testing Spring “session” scope

In a Spring based Web application, beans can be scoped to the user “session”. This essentially means that state changes to the session scoped bean are only visible in the scope of the user session.

The purpose of this entry is to simply highlight a way provided by Spring Test MVC to test components which have session scoped beans as dependencies.

Consider the example from Spring reference docs of a UserPreferences class, holding say the timeZoneId of the user:
 
 

@Component
@Scope(value="session", proxyMode=ScopedProxyMode.TARGET_CLASS)
public class UserPreferences {
 private String timeZoneId="default";
 public String getTimeZoneId() {
  return timeZoneId;
 }
 public void setTimeZoneId(String timeZoneId) {
  this.timeZoneId = timeZoneId;
 }
}

Here the scope is marked as “session” and the proxyMode is explicitly specified as TARGET_CLASS to instruct Spring to create a CGLIB proxy(as UserPreferences does not implement any other interface).

Now consider a controller making use of this session scoped bean as a dependency:

@Controller
public class HomeController {
 @Autowired private UserPreferences userPreferences;

 @RequestMapping(value="/setuserprefs")
 public String setUserPrefs(@RequestParam("timeZoneId") String timeZoneId, Model model) {
  userPreferences.setTimeZoneId(timeZoneId);
  model.addAttribute("timeZone", userPreferences.getTimeZoneId());
  return "preferences";
 }

 @RequestMapping(value="/gotopage")
 public String goToPage(@RequestParam("page") String page, Model model) {
  model.addAttribute("timeZone", userPreferences.getTimeZoneId());
  return page;
 }
}

Here there are two controller methods, in the first method the user preference is set and in the second method the user preference is read. If the session scoped bean is working cleanly, then the call to “/setuserprefs” in a user session should set the timeZoneId preference in the UserPreferences bean and a different call “/gotopage” in the same session should successfully retrieve the previously set preference.

Testing this is simple using Spring MVC test support now packaged with Spring-test module.

The test looks something like this:

First the bean definition for the test using Spring Java Configuration:

@Configuration
@EnableWebMvc
@ComponentScan({"scope.model","scope.services", "scope.web"})
public class ScopeConfiguration {}

and the test:

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpSession;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.context.WebApplicationContext;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ScopeConfiguration.class)
@WebAppConfiguration
public class ScopeConfigurationTest {

 @Autowired
 private WebApplicationContext wac;

 private MockMvc mockMvc;

 @Before
 public void setup() {
  this.mockMvc = webAppContextSetup(this.wac).build();
 }

 @Test
 public void testSessionScope() throws Exception {
  MockHttpSession mocksession = new MockHttpSession();
  this.mockMvc.perform(
    get("/setuserprefs?timeZoneId={timeZoneId}", "US/Pacific")
      .session(mocksession))
    .andExpect(model().attribute("timeZone", "US/Pacific"));

  this.mockMvc.perform(
    get("/gotopage?page={page}", "home")
     .session(mocksession))
    .andExpect(model().attribute("timeZone", "US/Pacific"));

  this.mockMvc.perform(
    get("/gotopage?page={page}", "home")
     .session(new MockHttpSession()))
    .andExpect(model().attribute("timeZone", "default"));
 }
}

In the test a MockHttpSession is first created to simulate a user session. The subsequent two requests are made in the context of this mock session, thus the same UserPreferences bean is expected to be visible in the controller which is asserted in the test. In the 3rd request a new session is created and this time around a different UserPreferences bean is visible in the controller which is asserted by looking for a different attribute.

This demonstrates a clean way of testing session scoped beans using Spring test MVC support.
 

Reference: Testing Spring “session” scope from our JCG partner Biju Kunjummen at the all and sundry blog.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

2 comments

  1. What are the details of this method?:

    webAppContextSetup()

Leave a Reply

Your email address will not be published. Required fields are marked *

*


− three = 1

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.