Wednesday, May 29, 2013

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:

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

public class HomeController {
 @Autowired private UserPreferences userPreferences;

 public String setUserPrefs(@RequestParam("timeZoneId") String timeZoneId, Model model) {
  model.addAttribute("timeZone", userPreferences.getTimeZoneId());
  return "preferences";
 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:
@ComponentScan({"scope.model","", "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.*;

public class ScopeConfigurationTest {
 private WebApplicationContext wac;

 private MockMvc mockMvc;

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

 public void testSessionScope() throws Exception {
  MockHttpSession mocksession = new MockHttpSession();
    get("/setuserprefs?timeZoneId={timeZoneId}", "US/Pacific")
    .andExpect(model().attribute("timeZone", "US/Pacific"));
    get("/gotopage?page={page}", "home")
    .andExpect(model().attribute("timeZone", "US/Pacific"));

    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.


  1. Isn't

    model.addAttribute("timeZone", userPreferences.getTimeZoneId());

    defeating the whole purpose of userPreferences, as you are just storing state in the model anyway?