承载令牌失败MockMvc测试Java Spring Boot

问题描述 投票:1回答:1

我无法理解为什么这不起作用。我假设它很简单,我忽略了。所有其他不使用令牌的其他测试方法都可以正常工作。令牌上目前没有过期,我可以使用Postman。

@Test
public void getUser() throws Exception {

    String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsd2lsbGlhbXMxNiIsInJvbGVzIjoidXNlciIsImlhdCI6MTUxNDQ0OTgzM30.WKMQ_oPPiDcc6sGtMJ1Y9hlrAAc6U3xQLuEHyAnM1FU";
    MvcResult mvcResult = mockMvc.perform(

            MockMvcRequestBuilders.get("/api/users/lwilliams16")
            .header("authentication", "Bearer " + token))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andDo(print())
            .andReturn();

    System.out.println(mvcResult.getResponse().getContentAsString());
}
java spring-boot bearer-token mockmvc
1个回答
0
投票

我使用的是Authentication而不是Authorization。晚了。此外,正确的响应类型是APPLICATION_JSON_UTF8。

@Test
public void getUser() throws Exception {

    String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJsd2lsbGlhbXMxNiIsInJvbGVzIjoidXNlciIsImlhdCI6MTUxNDQ0OTgzM30.WKMQ_oPPiDcc6sGtMJ1Y9hlrAAc6U3xQLuEHyAnM1FU";
    MvcResult mvcResult = mockMvc.perform(

            MockMvcRequestBuilders.get("/api/users/lwilliams16")
            .header("authorization", "Bearer " + token))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
            .andDo(print())
            .andReturn();

    System.out.println(mvcResult.getResponse().getContentAsString());
}
© www.soinside.com 2019 - 2024. All rights reserved.