Stubbing Entire Interfaces

Learn how to stub all of the functions in a mock module with the implementations in another module.

We don’t always want to use the mock module for every test. Imagine we have tests that cover a piece of code that internally calls rain?/2. In that case, we probably don’t want to set expectations on functions in the SoggyWaffle.WeatherAPIMock module since we don’t care about checking how the mock module is called. We want to stub the functions in SoggyWaffle.WeatherAPIMock so that they do the bare minimum to simulate that everything went smoothly when interfacing with the weather API. However, stubbing all the functions in each test that somehow end up calling get_forecast/1 becomes a pain quickly.

Stubbing all of the functions

The Mox.stub_with/2 function within Mox is used to stub all of the functions within the mock module with implementations in another module.

For example, we could define a NoOpWeatherAPI module that implements the SoggyWaffle.WeatherAPI.Behavior behavior but does absolutely nothing in the get_forecast/1 function.

Get hands-on with 1200+ tech skills courses.