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

About Biju Kunjummen

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:

@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.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.*;

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.

Reference: Testing Spring “session” scope from our JCG partner Biju Kunjummen at the all and sundry blog.
(0 rating, 0 votes)
You need to be a registered member to rate this.
2 Comments Views Tweet it!
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 ....
I agree to the Terms and Privacy Policy

Leave a Reply

1 Comment threads
1 Thread replies
Most reacted comment
Hottest comment thread
1 Comment authors
Jim C. Recent comment authors

This site uses Akismet to reduce spam. Learn how your comment data is processed.

newest oldest most voted
Notify of
Jim C.
Jim C.

What are the details of this method?:


Jim C.
Jim C.

Nevermind. :-) I didn’t see the static import:

import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup;