mockery v2.1.0 Mockery

Core functionality

Link to this section Summary

Functions

Function used to create mock in context of single test

Creates proxy to original module

Function used to prepare module for mocking

Link to this section Types

Link to this type erlang_module()
erlang_module() :: atom()

Link to this section Functions

Link to this function mock(mod, fun, value \\ :mocked)

Function used to create mock in context of single test.

Mock created in one test won’t leak to another. It can be used safely in asynchronous tests.

Mocks can be created with static value:

mock Mod, [fun: 2], "mocked value"

or function:

mock Mod, [fun: 2], fn(_, arg2) -> arg2 end

Keep in mind that function inside mock must have same arity as original one.

This:

mock Mod, [fun: 2], &to_string/1

will raise an error.

It is also possible to mock function with given name and any arity

mock Mod, :fun, "mocked value"

but this version doesn’t support function as value.

Also, multiple mocks for same module are chainable

Mod
|> mock(:fun1, "value")
|> mock([fun2: 1], &string/1)
Link to this function new(mod, opts \\ [])
new(mod :: module() | erlang_module() | String.t(), opts :: [{:by, module() | String.t()}] | []) :: proxy_tuple()

Creates proxy to original module.

In contrast to Mockery.of/2 it always returns proxy no matter what environemnt is returned by Mix.env/0. User have to explicitely prepare module for mocking through application configs.

# module
@foo Application.get_env(:my_app, :foo, MyApp.Foo)

# MIX_ENV=test iex -S mix
iex(1)> Mockery.new(MyApp.Foo)
{Mockery.Proxy, MyApp.Foo, nil}

# config/test.exs
config :my_app, :bar, {Mockery.Proxy, MyApp.Foo, nil}
Link to this function of(mod, opts \\ [])
of(mod :: module() | erlang_module() | String.t(), opts :: [{:by, module() | String.t()}] | []) ::
  module() |
  proxy_tuple()

Function used to prepare module for mocking.

For Mix.env other than :test it returns the first argument unchanged. For Mix.env == :test it creates a proxy to the original module. When Mix is missing it assumes that env is :prod

@elixir_module Mockery.of("MyApp.Module")
@erlang_module Mockery.of(:crypto)

It is also possible to pass the module in elixir format

@module Mockery.of(MyApp.Module)

but it is not recommended as it creates an unnecessary compile-time dependency (see mix xref graph output for both versions).