My Mock Solution For Elixir Apps

May 14, 2020

After working through various options for mocking in Elixir, I decided to take the advice of the language author and go with an approach that I’ve often considered, but never actually tried.

Instead of using a library to hijack requests and return fake data, I created a fake version of the module I was mocking that returns the request I would get. I also set up some configuration to load the correct module. And then created some functions to call them.

Worth noting that I didn’t use any library.

Fakes look like this.

defmodule MyModule.FakeModule do
  def get(settings, config) do
    {:ok, %{some: data}

Each environment config has a line like this.

config :my_app, :my_module, MyModule.FakeModule

config :my_app, :my_module, MyModule

config :my_app, :my_module, MyModule

Then in the actual module, I have this function

defp my_module() do
  Application.get_env(:my_app, :my_module)

Then when I need to call the get() function, I use my_module().get(settings, config), and it calls the appropriate module.

I’m a fan of this approach so far. I don’t like how the fake modules sprinkled in the lib directory. I’m sure there is a better way, but I really like the extraction and clarity of the fakes.

More stuff:

or go see everything in the archive.