Spring Junit与会话对象-不可见的控制器



简单测试类有以下内容:

@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?缺少了什么?div . .

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

可以手动添加。

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

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

相关内容

  • 没有找到相关文章

最新更新