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 assertedCheers
No comments:
Post a Comment