Recommended Strategies for testing 3rd Party APIs?

I have a couple Elixir modules that rely in part on 3rd party APIs. I’m wondering how I can best test them? Since the 3rd party service may be down or we may experience time-outs or we may have mis-configured the connection entirely, it is important that our module can recover and log any problems.

One gotcha is that Elixir reads ENV variables at compile-time. If I wanted to test that the proper URL had been entered, I would have to restructure my module and functions to allow for me to inject an override. Is this recommended?

Another not-so-hypothetical case is that our account with the 3rd party may have lapsed – let’s say our contract expired without anyone noticing. In that case, our API token would stop working and their API would start returning an error page. Again, I could refactor our modules so that I could inject a fake response, but it seems like that approach is not idiomatic to Elixir.

Any suggestions? Thanks!

Jose wrote about mocks a while ago: Mocks and explicit contracts.

Long story short, it involves configuring implementations of APIs per environment but mandates you create a behaviour which serves as a contract.

As for 3rd party APIs erroring, I am not sure what your question really is; if the API starts erroring out surely you can catch the {:error, reason} tuples in your calling functions and react accordingly? Sorry if I misunderstood your problem there.

1 Like

Thanks, I’ll look at that article. The point with the 3rd party API is that we don’t know if or when it will throw errors, but in order to test our implementation we need to be able to simulate those responses.

Then maybe Bypass will be of help. See BleacherReport’s article about it.