Tuesday, July 16, 2013

Spring MVC testing with session scoped beans

Spring MVC test is a new feature from Spring 3.2 that could help easy function/integration testing with the controller without bring up a real server. However, when controller autowiring  a session scoped bean and some controller request mapping methods have operations on the bean, how to make assertion on those operations becomes tricky. Here I will propose an approach to test against it.

Assume there is a session scoped bean configured as below:

@Scope(value= "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class SessionScopeBean {
 private String value;

 public String getValue() {
  return value;

 public void setValue(String value) {
  this.value = value;
There is a controller autowired with the session scoped bean
public class HomeController {
 private SessionScopeBean sessionBean;
 @RequestMapping(value = "/sessionScope/{value}")
 public String test(@PathVariable String value){
  return "home";
The above controller modify the value field of a session scope bean, then how would we retrieve that and assert the appropriate value in the session. Couple of tips here:

  • Spring saves the session scope bean as a session attribute "scopedTarget.${idOfTheBean}"
  • Spring mvc test provides request().sessionAttribute("attr", hamcrestMatcher) to assert the session
  • hamcrest matcher HasPropertyWithValue can be used to inject into the above expression

public class ControllerTest {
 private MockMvc mockMvc;
 private WebApplicationContext wac;
 public void setup(){
  this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
 public void test() throws Exception{
   andExpect(request().sessionAttribute("scopedTarget.sessionScopeBean", hasProperty("value", is("abc"))));
The above tests shows how the session attribute being asserted


No comments:

Post a Comment