首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >spring session与MockHttpSession不兼容

spring session与MockHttpSession不兼容
EN

Stack Overflow用户
提问于 2017-06-22 15:19:18
回答 1查看 958关注 0票数 2

当我尝试集成spring session时,以下测试失败。

代码语言:javascript
复制
class WeChatOAuth2AuthenticationFilterTest extends AbstractWebMvcTest {

    @Test
    void it_should_redirect_user_to_origin_uri_when_wechat_oauth_is_finished() throws Exception {

        String code = "codeToExchangeWeChatUserAccessToken"
        String plainUrl = "http://www.example.com/index.html?a=b#/route"
        String state = Base64.getUrlEncoder().encodeToString(plainUrl.getBytes("UTF-8"))
        WxMpOAuth2AccessToken accessToken = new WeChatUserOAuth2AccessTokenFixture().buildToken()

        given(wxMpService.oauth2getAccessToken(code))
                .willReturn(accessToken)

        this.mockMvc.perform(get("/wechat/oauth/token")
                .param("state", state) 
                .param("code", code))
                .andDo(print())
                .andExpect(status().is3xxRedirection())
                .andExpect(redirectedUrl(plainUrl)) 
                .andExpect(authenticated()) 
                // throws Authentication should not be null
    }   
}

@Configuration
@EnableSpringHttpSession
public class HttpSessionConfig {

    @Bean
    protected SessionRepository sessionRepository() {
        return new MapSessionRepository();
    }
}

经过调试,我发现这可能是因为我无法获取HttpSession

代码语言:javascript
复制
// org.springframework.security.web.context.HttpSessionSecurityContextRepository
public SecurityContext loadContext(HttpRequestResponseHolder requestResponseHolder) {
        HttpServletRequest request = requestResponseHolder.getRequest();
        HttpServletResponse response = requestResponseHolder.getResponse();
        HttpSession httpSession = request.getSession(false); 
        //returns null with spring-session, 
        //returns a MockHttpSession instance without spring-session

        SecurityContext context = readSecurityContextFromSession(httpSession);

目前,我使用@ConditionalProperties为测试禁用了spring会话。欢迎任何更好的想法。

EN

回答 1

Stack Overflow用户

发布于 2017-12-31 08:38:57

这与测试中mockMvc对象的正确设置有关。

为简洁起见,我假设您可以在项目中使用@SpringBootTest注释。下面的代码展示了如何正确地将spring-session相关的类连接到mockMvc中。

代码语言:javascript
复制
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
public class ExampleControllerV2SpringSessionTest {

@Autowired
private WebApplicationContext wac;

@Autowired
private SessionRepository sessionRepository;

@Autowired
private SessionRepositoryFilter sessionRepositoryFilter;

//this is needed to test spring-session specific features
private MockMvc mockMvcWithSpringSession;

@Before
public void setup() throws URISyntaxException {

    this.mockMvcWithSpringSession = MockMvcBuilders
       .webAppContextSetup(wac)
       .addFilter(sessionRepositoryFilter)
       .build();
}


//------------------------- BEGIN: Test cases with Spring-session---------------------------------

@Test
public void getANewSpringSession(String requestBody) throws Exception {
    MvcResult result = mockMvcWithSpringSession.perform(
            get("/v1/sampleendpoint")                    .header("YOUR_HEADER_NAME", "YOUR_HEADER_VALUE")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content("YOUR_SAMPLE_JSON_BODY"))
            .andExpect(status().isOk())
            .andExpect(header().string("x-auth-token", notNullValue()))
            .andReturn();

    String xAuthToken = result.getResponse().getHeader(AuthenticationControllerV2.Params.SESSION_KEY);
    MapSession curSession = (MapSession) sessionRepository.getSession(xAuthToken);
    Assert.assertNotNull(curSession);
}

//------------------------- END: Test cases with Spring-session---------------------------------

}

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44692666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档