How Mox works: The Mocking Workflow
mainMox follows a specific pattern to enable concurrent, behaviour-based mocking:
- Define a Behaviour: Create a module that defines the contract (the functions and their signatures) using
@callback. - Provide an Implementation: Create a real module that implements that behaviour for production use.
- Implement a Switch: In your application code, do not call the implementation directly. Instead, fetch the implementation module from an application configuration (e.g.,
Application.get_env/2). This allows you to swap the real implementation for a mock during tests. - Define the Mock: In your
test_helper.exs, useMox.defmock/2to create a mock module based on your behaviour, and then update your application configuration to point to this new mock module. - Use
expect/3in Tests: In your test files, useexpect/3to define how the mock should respond to specific arguments and to assert that the correct arguments were received.