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:

@Component
@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
@Controller
public class HomeController {
 
 @Autowired
 private SessionScopeBean sessionBean;
  
 @RequestMapping(value = "/sessionScope/{value}")
 public String test(@PathVariable String value){
  sessionBean.setValue(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


@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration("classpath:test-appContext.xml")
public class ControllerTest {
 
 private MockMvc mockMvc;
 
 @Autowired
 private WebApplicationContext wac;
 
 
 
 @Before
 public void setup(){
  this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
 }
 
 @Test
 public void test() throws Exception{
  mockMvc.perform(get("/sessionScope/abc")).
   andExpect(view().name("home")).
   andExpect(request().sessionAttribute("scopedTarget.sessionScopeBean", hasProperty("value", is("abc"))));
 }
}
The above tests shows how the session attribute being asserted

Cheers

No comments:

Post a Comment