带有弹簧启动的oauth2集成测试

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

我在为应用程序编写集成测试时遇到问题。手动测试集成可以按预期完美地工作;编写集成测试时遇到问题。我遵循了https://www.baeldung.com/oauth-api-testing-with-spring-mvc中的指南,但是它似乎不适用于我的应用程序。 (不确定是否是因为我使用的是JUnit5)。我真的不知道我到底缺少什么。该请求始终以禁止的401末尾响应,而不是在发布请求中设置新访问令牌的200响应。

application.yml

spring:
  profiles: test
security:
  oauth:
    client:
      client-id: client-id
      client-secret: client-secret

IntegrationTest

@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("test")
public class MyIntegrationTest {

    private MockMvc mvc;

    @Autowired
    private FilterChainProxy filterChainProxy;

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Value("${security.oauth2.client.client-id}")
    private String clientId;

    @Value("${security.oauth2.client.client-secret}")
    private String clientSecret;

    @BeforeEach
    public void setUp() {
        mvc = MockMvcBuilders
                .webAppContextSetup(webApplicationContext)
                .addFilter(filterChainProxy).build();
    }

    private String obtainAccessToken() throws Exception {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "client_credentials");
        params.add("client_id", clientId);
        params.add("client_secret", clientSecret);
        params.add("scope", "any");

        String mvcResult = mvc.perform(post("/oauth/token")
            .params(params)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON))
            .andReturn()
            .getResponse().getContentAsString();

        return new JacksonJsonParser().parseMap(mvcResult).get("access_token").toString();
    }


}

java spring-boot junit mockmvc
1个回答
0
投票

您需要更改:

MediaType.APPLICATION_JSON

至:

MediaType.APPLICATION_JSON_UTF8_VALUE
© www.soinside.com 2019 - 2024. All rights reserved.