简体   繁体   中英

How to unit test 3rd party API endpoints that need access_token?

I'm developing a backend API that consumes Github's API to retrieve some repos and do some stuff with it. Also I'm using Codeship CI , so all my data need to be in the code in order to be properly built.

There's a route in my backend /api/github/repos that takes an Github access_token as parameter and consumes https://api.github.com/user/repos endpoint which lists all logged user repositories.

My doubt is: how do I unit test this route? I cannot write my access_token in the unit test since it's sensitive data and I'm storing it in Github public repository nor I can seed that data to a database because the access_token will still be written in the code. Where should I keep my access_token ? Is there another approach?

I'm developing in PHP using Laravel framework but as you can see this problem is language independent.

There are multiple ways you can do this:

  1. Use a test table / file (or .env) / cache key value pair, store the api key in the test table / file / cache and then retrieve the key in the unit test, which passes the params to the request for testing
  2. Pass command line arguments to phpunit
  3. Use a repository interface to fetch the api key in your controller class. You can have 2 repository class implementations of this interface - the first fetching the key from the request param and the second fetching the key from say a test table / file / cache as in point #1

There may be other ways as well. Which one you choose would depend on your app. If the api key is relevant for most unit tests, you may go for #2, else #1. #3 would be ideal for large apps - more layers of abstraction and cleaner code but over-engineering for small/mid apps

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