Easy Mocking in Erlang

Working on yarmo and trying to do test driven development I ran into need to mock some modules to avoid need for hitting database every time. After a bit of trying and errors I ended up using pretty simple set up based on parametrized modules. Basic idea is to pass a proplist, with mock responses for methods I am trying to mock, into the module as module parameter and have methods look it up:

-module(mock_store, [MockStore]).
-export([read/1, create/1]).

read(Key) ->
	callback(read, [Key]).

create(Key, Document) ->
	callback(create, [Key, Document]).

%% Helper Functions

callback(Name, Args) ->
	case proplists:lookup(Name, MockStore) of
		none -> undefined;
		{Name, Fun} when is_function(Fun) -> Fun(Args);
		{Name, Value} -> Value

The callback is pretty simple, but allows to pass in ether mock result or a function, which will generate response based on parameters, passed to the method.
Now I can mock read/create in the test as following:

test_mod(StoreOptions) ->
	Store = mock_store:new(StoreOptions),


Mod = test_mod([{read, not_found}]),

Mod = test_mod([{read, fun([Key]) -> ?assertEqual("sample", Key), Doc end}])

Nothing special, but so far it is helping me to keep my tests from hitting real storage 🙂


About Wondering Bear
39 years old male bear.

2 Responses to Easy Mocking in Erlang

  1. morman says:


    This looks simple and easy.

    Apparently there is a “emock” thing too for services:


    but I’ve not really looked at it, and I don’t know if it does storage.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: