具有会话对象的Spring Junit - 在Controller中不可见

时间:2015-06-01 17:16:21

标签: java spring session junit spring-junit

Simple Test类具有以下内容:

@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());
}

...

Controller类具有以下内容:

@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
}

问题:为什么会话没有FOO?缺什么? ..

1 个答案:

答案 0 :(得分:2)

我不认为Spring可以自动链接MockHttpSession(我也不知道你在哪里自动装配它)。

您可以手动添加。

RequestBuilder requestBuilder = MockMvcRequestBuilders.post("/setSomeType")
            .param("someType", "ACCESS_ONLY")
            .accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
            .session(session);

或者,您可以使用sessionAttr(String, Object)单独添加会话属性。