简体   繁体   English

具有会话支持的Spring mvc 3.1集成测试

[英]Spring mvc 3.1 integration tests with session support

I'm using the new spring-test in the 3.1 version to run integration tests. 我正在使用3.1版本中的新弹簧测试来运行集成测试。 It works really well but I can't make the session to work. 它工作得很好,但我不能使会话工作。 My code: 我的代码:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration("src/main/webapp")
@ContextConfiguration({"classpath:applicationContext-dataSource.xml",
      "classpath:applicationContext.xml",
      "classpath:applicationContext-security-roles.xml",
      "classpath:applicationContext-security-web.xml",
      "classpath:applicationContext-web.xml"})
public class SpringTestBase {

    @Autowired
    private WebApplicationContext wac;
    @Autowired
    private FilterChainProxy springSecurityFilterChain;
    @Autowired
    private SessionFactory sessionFactory;

    protected MockMvc mock;
    protected MockHttpSession mockSession;

    @Before
    public void setUp() throws Exception {
       initDataSources("dataSource.properties");

       mock = MockMvcBuilders.webAppContextSetup(wac).addFilters(springSecurityFilterChain).build();
       mockSession = new MockHttpSession(wac.getServletContext(), UUID.randomUUID().toString());
    }

    @Test
    public void testLogin() throws Exception {
        // this controller sets a variable in the session
        mock.perform(get("/")
            .session(mockSession))
            .andExpect(model().attributeExists("csrf"));

        // I set another variable here just to be sure
        mockSession.setAttribute(CSRFHandlerInterceptor.CSRF, csrf);

        // this call returns 403 instead of 200 because the session is empty...
        mock.perform(post("/setup/language")
            .session(mockSession)
            .param(CSRFHandlerInterceptor.CSRF, csrf)
            .param("language", "de"))
            .andExpect(status().isOk());
    }
}

My session is empty in every request, I don't know why. 我的会话在每个请求中都是空的,我不知道为什么。

EDIT: The last assert is failing: andExpect(status().isOk()); 编辑:最后一个断言失败: andExpect(status().isOk()); . It returns 403 instead of 200. 它返回403而不是200。

UPDATED ANSWER: 更新的答案:

It seems a new method "sessionAttrs" has been added to the builder (see mvc controller test with session attribute ) 似乎在构建器中添加了一个新的方法“sessionAttrs”(参见带有session属性的mvc控制器测试

Map<String, Object> sessionAttrs = new HashMap<>();
sessionAttrs.put("sessionAttrName", "sessionAttrValue");

mockMvc.perform(MockMvcRequestBuilders.get("/uri").sessionAttrs(sessionAttrs))
      .andDo(print())
      .andExpect(MockMvcResultMatchers.status().isOk());

OLD ANSWER: 老答案:

here is a simpler solution to achieve the same result without using supporting classes, this is a snippet of my code (I don't know if these methods had been already available when Biju Kunjummen answered): 这是一个更简单的解决方案,可以在不使用支持类的情况下获得相同的结果,这是我的代码片段(我不知道这些方法在Biju Kunjummen回答时是否已经可用):


        HttpSession session = mockMvc.perform(post("/login-process").param("j_username", "user1").param("j_password", "user1"))
            .andExpect(status().is(HttpStatus.FOUND.value()))
            .andExpect(redirectedUrl("/"))
            .andReturn()
            .getRequest()
            .getSession();              

        Assert.assertNotNull(session);

        mockMvc.perform(get("/").session((MockHttpSession)session).locale(Locale.ENGLISH))
            .andDo(print())
            .andExpect(status().isOk()) 
            .andExpect(view().name("logged_in"));

I have done this in a somewhat roundabout manner - works though. 我以一种有点迂回的方式做到了这一点 - 尽管如此。 What I did was to let Spring-Security create a session with the relevant Security attributes populated in the session and then grab that session this way: 我所做的是让Spring-Security创建一个会话,其中包含会话中填充的相关安全属性,然后以这种方式获取该会话:

    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 hold the session: SessionHolder是我的自定义类,只是为了保存会话:

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 extending from MockHttpSession, just because the session method requires MockHttpSession: 而SessionWrapper是从MockHttpSession扩展的另一个类,因为会话方法需要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 these set, now you can simply take the session from the sessionHolder and execute subsequent methods, for eg. 使用这些set,现在您可以简单地从sessionHolder获取会话并执行后续方法,例如。 in my case: 在我的情况下:

mockMvc.perform(get("/membersjson/1").contentType(MediaType.APPLICATION_JSON).session(sessionHolder.getSession()))
            .andExpect(status().isOk())
            .andExpect(content().string(containsString("OneUpdated")));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM