Elixir Mocking Library Options

There are many options in the Elixir ecosystem for mocking. There are a few that stand out in my mind as nicer than others. Especially Mimic and Hammox.

When coming to Elixir from another language such as Node.js or Ruby it can be a bit difficult to discern which mocking library you ought to incorporate, as there are a number of different options, with varying levels of community endorsement, and varying levels of difficulty in integrating them into your code base that may or may not be immediately visible based on reading the documentation.

  • Mox
    At first glance Mox would appear to be the obvious choice, given that it's been created by the incredible folks at Dashbit, some of the core Elixir folks. But while you'll find it's ideal of providing and ensuring contracts are met is noble, you'll be cluttering your code base with module attributes that are actually modules in a way that decreases overall readability. Then after you've done that you'll find out that in actuality it doesn't enforce the contracts that you actually brought it in to mock and then enforce.
  • Hammox
    I haven't yet used Hammox as a point of full disclosure, but given that it stems from the same pain of having not actually had contracts verified, and attempting to address this it seems like it could be a huge win. You'll still have the module attributes potentially littering your code base, but that may not necessarily be a bad thing, as it would serve to discourage mocking, rather than utilizing the actual function.
  • Mimic
    My personal favorite, to with some gotchas to be detailed in a future post, but allows for adhoc mocks to occur, without contract verification, but also without having to inject modules via module attributes, but by mocking the actual module in play. You can also work around the pain of the lack of validation somewhat by utilizing Dialyzer.
  • Meck
    I haven't actually used Meck, due the fact that it's an Erlang library, and due to having found other Elixir libraries first. While I'm not opposed to using Erlang libraries as an Elixir developer, I prefer using one of the other listed libraries.
  • Mock
    Another fair library that I've used in the past, that allows for very explicit mocks without littering your code base, but one that I found a bit syntactically wordy compared to Mimic.

At the end of the day for a new Elixir project I'd recommend checking out Mimic or Hammox for your mocking needs.