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
	end.

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),
	yarmo_destination:new(Store).

....

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 🙂