Simple Test class have the following:
@Autowired
private WebApplicationContext wac;
@Autowired
MockHttpSession session;
private MockMvc mockMvc;
@Before
public void before() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testSetSomeType() throws Exception {
this.session.putValue("PREV_PAGE_VAL", "FOO");
System.out.println(this.session.getAttribute("PREV_PAGE_VAL")); //FOO is there, so far so good, but in the controller, its null
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/setSomeType").param("someType", "ACCESS_ONLY").session(session)
.accept(MediaType.parseMediaType("application/json;charset=UTF-8"));
ResultActions result = this.mockMvc.perform(requestBuilder);
result.andExpect(MockMvcResultMatchers.status().isOk());
}
..
And the Controller class has the following:
@RequestMapping(value = "/setSomeType", method = RequestMethod.POST)
public @ResponseBody AppResponse setSomeType(@RequestParam(value = "someType") final String someType, final HttpSession session) {
//someType has "ACCESS_ONLY"
//session.getAttribute("PREV_PAGE_VAL"); is null, expecting FOO
}
Question: Why is session not having the FOO? What is missing? ..
I don't think Spring can automatically link a MockHttpSession
(I also don't know where you're autowiring it from).
You can add it manually.
RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/setSomeType")
.param("someType", "ACCESS_ONLY")
.accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
.session(session);
Alternatively, you can use sessionAttr(String, Object)
to add session attributes individually.