In BlogPost, Elixir

Mocking HTTP API tests with Phoenix and Elixir

Recently, I needed to write a test based on a return value from calling the YouTube API. Being new to Elixir and Phoenix and coming from Ruby on Rails, I surmised I had a few options.

elixir basics

Option 1: Mock the test

I could mock out a test. This would save a lot of time, and provided they are done properly with an explicit contract as pointed out in this post by José Valim, they can be a good way to go.

Option 2: Real-time testing

I could try and hit the HTTP endpoint every time. Or I could try and use a library similar to the vcr gem in the Ruby world. There’s one called exvcr apparently.

Choose mocking – Option 1

In the end, I chose to mock the test. I chose it so that I wouldn’t have to add another dependency (exvcr plugin) and I would pay the cost of doing real-time testing.

Step 1: Setup a mock library

The first step is to create a mocking library that you are going to swap out in the actual code that relies on your HTTP library calling code.

As an example, let’s say you have a module called VideoDataFetcher that uses another module called YouTubeFetcher which pulls data via the YouTube API.

I would create another module called YouTubeFetcher.Mock that would return mocked out results from the YouTube API. This would be used in the VideoDataFetcher class.

To give you a visual idea, here’s some sample code:

The YouTubeFetcher is responsible for making calls to the YouTube API.

The YouTubeFetcher.Mock is responsible for returning “mocked” HTTP responses.

Step 2: Setup the corresponding module so it can use the mock library

The VideoFetcher makes use of the YouTubeFetcher class. Some function definitions have been omitted for brevity.

Step 3: Configure environment variables in the config directory for each environment

The next step is to configure the YouTubeFetcher library for use with development and production and to configure the YouTubeFetcher.Mock for use with test environment.

config/test.exs

config/dev.exs

Step 4: Write your tests

Next populate the test directory and run mix test. Because you already set the configuration in config/test.exs, the test suite knows to use the YouTubeFetcher.mock library.

Summary

If you want to mock an HTTP API response for testing in Elixir, it’s fairly straightforward to do so. Just follow Steps 1-4 above.

Recent Posts