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

Each environment config has a line like this.

Test
config :my_app, :my_module, MyModule.FakeModule

Dev
config :my_app, :my_module, MyModule

Prod
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)
end

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.