gpt4 book ai didi

java - spring session 与 MockHttpSession 不兼容

转载 作者:行者123 更新时间:2023-12-05 05:20:23 24 4
gpt4 key购买 nike

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

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导致的

// 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 session 。欢迎任何更好的想法。

最佳答案

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

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

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

关于java - spring session 与 MockHttpSession 不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44692666/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com