java - oauth2 与 Spring Boot 集成测试

标签 java spring-boot junit mockmvc

我在为我的应用程序编写集成测试时遇到问题。手动测试集成按预期工作得很好;只是在编写集成测试时遇到问题。我按照 https://www.baeldung.com/oauth-api-testing-with-spring-mvc 的指南进行操作,但它似乎不适用于我的应用程序。 (不确定是否是因为我使用的是 JUnit5)。我真的不知道我到底错过了什么。该请求最后继续响应,并在设置新访问 token 的 POST 请求中返回 401 禁止,而不是 200。

应用程序.yml

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

集成测试

@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();
    }


}

最佳答案

您需要更改此设置:

MediaType.APPLICATION_JSON

对此:

MediaType.APPLICATION_JSON_UTF8_VALUE

或者这个,如示例所示:

"application/json;charset=UTF-8"

关于java - oauth2 与 Spring Boot 集成测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61159147/

相关文章:

java - 在 Java 中将 xml 文件转换为 excel

unit-testing - 使用 Thymeleaf 模板引擎对服务进行单元测试时出现问题

java - 如何使@SpringBootTest使用可配置属性

java - 带斜杠和点的 RequestMapping

java - 使用 jmock 状态覆盖每个测试用例的期望

java - 通过 Java 枚举值填充 XML 文件中的属性值

java - java中按两个字段对对象进行分组

java - 当我的代码不使用 ArrayLIst 时,为什么 ArrayList.java 会出现 NullPointerException 错误?

java - 在 Groovy 中解析 JSON 数组

java - 如何在 Java 项目中查找 jUnit 测试?