I did this in a somewhat workaround - it works. What I did was let Spring-Security create a session with the appropriate security attributes populated in the session, and then grab that session as follows:
this.mockMvc.perform(post("/j_spring_security_check") .param("j_username", "fred") .param("j_password", "fredspassword")) .andExpect(status().isMovedTemporarily()) .andDo(new ResultHandler() { @Override public void handle(MvcResult result) throws Exception { sessionHolder.setSession(new SessionWrapper(result.getRequest().getSession())); } });
SessionHolder is my custom class, just to host a session:
private static final class SessionHolder{ private SessionWrapper session; public SessionWrapper getSession() { return session; } public void setSession(SessionWrapper session) { this.session = session; } }
and SessionWrapper is another class that extends from MockHttpSession, just because the session method requires MockHttpSession:
private static class SessionWrapper extends MockHttpSession{ private final HttpSession httpSession; public SessionWrapper(HttpSession httpSession){ this.httpSession = httpSession; } @Override public Object getAttribute(String name) { return this.httpSession.getAttribute(name); } }
With this set, now you can simply take a session from sessionHolder and execute the following methods, for example. in my case:
mockMvc.perform(get("/membersjson/1").contentType(MediaType.APPLICATION_JSON).session(sessionHolder.getSession())) .andExpect(status().isOk()) .andExpect(content().string(containsString("OneUpdated")));
Biju Kunjummen Dec 03 2018-12-12T00: 00Z
source share