Test Doubles: Stubs, Mocks, and Fakes

Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (25 / 80)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Interfacing to External Dependencies with Beha viours | TOC | The Hidden Benefits of Dependency Doubles 👉

Until now, we’ve just used the term external dependency double to refer to something that doubles as the external dependency. However, we can be more precise than that and define three kinds of doubles: stubs, mocks, and fakes. We already saw an example of a fake with SoggyWaffle.FakeWeatherAPI. A fake is just something that acts as the external dependency without calling out to the external dependency. A stub is a double where function implementations can be replaced on demand to do something in isolation, for example by replacing a function to do something in one test and something else in another. Stubs can be used to provide a different behavior of a given function based on the need of the test. Stubs are most useful when combined with mocks. A mock is essentially a stub that can be used for asserting on how and how many times the double is called.

Stubs and mocks require a little more work than fakes, since we have to be able to work with the specific functions of an interface instead of faking the whole interface at once. Luckily, in Elixir we can use a library called Mox.[14] Mox lets us define test doubles based on behaviours and provides functionalities to make mocks or stubs of single functions in the behaviour. The library works by defining dynamic modules on demand that…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.