简体   繁体   中英

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

I have a client service like this,

@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
    }
  }
}

Now the rest template here that I am using is secured with OAuth2 implementation and it is using client_id and secret with grant_type as client_credentials to generate a token and then using this token as header to call the EXTERNAL_API

I am following this guide here but it's not really helpful since it is using JUnit4 and I am on JUnit5: https://www.baeldung.com/oauth-api-testing-with-spring-mvc

I'm confused. What do you want to test?

The sample you link is achieving controller unit-testing with mockmvc.

They use an annotation which loads security context. As a consequence test security context must be configured for the request to reach controller endpoint.

I don't see any security rules on your service (@PreAuthorize or something) => you don't need any security context, just don't load security config.

If you add security rules you want to unit test, load security config and setup test security context (either explicitly or with something like https://github.com/ch4mpy/spring-addons/tree/master/samples/webmvc-jwtauthenticationtoken/src/test/java/com/c4_soft/springaddons/samples/webmvc_jwtauthenticationtoken )

The call to external service is a complete different story: the external service is running with a different security context than the one attached to your tested service thread). Either:

  • @MockBean RestTemplate (and configure mock for the Rest call your service is issuing) => unit test
  • ensure test configuration for RestTemplate and external service points to the same started authorization server, load rest template config, auto wire RestTemplate as normal and let it issue request for real to actual external service (which must be started too) => integration test.

You should not start with integration test. Unit test are for more stable and easier to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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