繁体   English   中英

如何在 JUnit5 中为使用 OAuth2 保护的 REST API 编写集成测试?

[英]How do I write an integration test for a REST API secured with OAuth2 in JUnit5?

我有这样的客户服务,

@Service
public class PersonClientService {
  private final String EXTERNAL_API;
  private RestTemplate restTemplate;

  @Autowired
  public PersonClientService(RestTemplate restTemplate, @Value("${person.url}") String apiUrl) {
    this.restTemplate = restTemplate;
    EXTERNAL_API = apiUrl
  }

  public ResponseDTO createData(PersonDTO personDTO) throws Exception {
    try {
      HttpEntity<PersonDTO> input = new HttpEntity<>(personDTO);
      ResponseEntity<ResponseDTO> restponseDTO = restTemplate.exchange(EXTERNAL_API, HttpMethod.POST, input, ResponseDTO.class);
      return responseDTO.getBody();
    } catch(Exception e) {
      //catch exception
    }
  }
}

现在,我在这里使用的其余模板通过 OAuth2 实现得到保护,它使用client_idsecret以及grant_type作为client_credentials来生成令牌,然后使用这个令牌作为标头来调用EXTERNAL_API

我在这里遵循本指南,但它并没有真正的帮助,因为它使用的是 JUnit4,而我使用的是 JUnit5: https ://www.baeldung.com/oauth-api-testing-with-spring-mvc

我很困惑。 你想测试什么?

您链接的示例是使用 mockmvc 实现控制器单元测试。

他们使用加载安全上下文的注释。 因此,必须为到达控制器端点的请求配置测试安全上下文。

我在您的服务上看不到任何安全规则(@PreAuthorize 或其他东西)=>您不需要任何安全上下文,只是不要加载安全配置。

如果您添加要进行单元测试的安全规则,请加载安全配置并设置测试安全上下文(显式或使用类似https://github.com/ch4mpy/spring-addons/tree/master/samples/webmvc-jwtauthenticationtoken/ src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken

对外部服务的调用是一个完全不同的故事:外部服务运行的安全上下文与附加到您测试的服务线程的安全上下文不同)。 任何一个:

  • @MockBean RestTemplate (并为您的服务发出的 Rest 调用配置模拟)=> 单元测试
  • 确保 RestTemplate 和外部服务的测试配置指向同一个启动的授权服务器,加载 rest 模板配置,正常自动连接 RestTemplate 并让它发出对实际外部服务的请求(也必须启动)=> 集成测试。

您不应该从集成测试开始。 单元测试是为了更稳定和更容易维护。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM