使用标头在Spring中执行get请求

时间:2018-02-22 05:10:10

标签: junit spring-security

我正在编写一个测试我的WebSecurity配置的单元测试。

这是我的测试:

@Test
public void access_to_a_protected_url_with_good_credentials_return_ok() throws Exception {
    String accessToken = Base64.getEncoder().encodeToString(("user:password").getBytes());

    MvcResult result = mvc.perform(get("/protected")
            .header("Authorization", "Basic " + accessToken))
            .andExpect(status().isOk());
}

有没有办法在不使用我正在做的方式传递授权令牌的情况下简化此测试?

1 个答案:

答案 0 :(得分:0)

与您类似的一种方法是使用MockHttpServletRequestBuilder

构建请求
@Test
public void access_to_a_protected_url_with_good_credentials_return_ok() throws Exception {
    String accessToken = Base64.getEncoder().encodeToString(("user:password").getBytes());

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.add("Authorization", "Bearer "+accessToken);

    MockHttpServletRequestBuilder mockReqBuilder = get("/protected").headers(httpHeaders);

    ResultActions actions = mockMvc.perform(mockReqBuilder);
    actions.andExpect(status().isOk());        

}

我是否正确理解了您的问题?