mockery v1.4.0 Mockery

Core functionality

Link to this section Summary

Functions

Function used to create mock in context of single test

Function used to prepare module for mocking

Link to this section Types

Link to this type keyword_opts()
keyword_opts() :: [{atom, any}]

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 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:

mock Mod, :fun, &string/1

doesn’t make any sense, because it will only work for Mod.fun/1.

Also, multiple mocks for same module can be chainable

Mod
|> mock(:fun1, "value")
|> mock([fun2: 1], &string/1)
Link to this function of(mod, opts \\ [])
of(mod :: atom | String.t, opts :: keyword_opts) ::
  module |
  proxy

Function used to prepare module for mocking.

For MIX_ENV other than :test it returns first argument unchanged. For test env it creates kind of proxy to oryginal module.

Proxy can be implicit

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

or explicit

@elixir_module Mockery.of("MyApp.Module", by: "MyApp.FakeElixirModule")
@erlang_module Mockery.of(:crypto, by: "MyApp.FakeErlangModule")

Explicit version is used for global mocks. For more information see Mockery.Heritage.

It is also possible to pass module in elixir format

@module Mockery.of(MyApp.Module, by: MyApp.FakeElixirModule)

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