[erlang-questions] Mocking in Erlang

Christian S <>
Sat Jun 7 18:57:09 CEST 2008

> True. And something I would like even better is if I could generate
> that module in a few lines close to the eunit test function. (Cant be
> impossible to create a module directly from a list of atoms and funs.
> Doesnt need to be fast.)
> A downside is that the module namespace is node-wide, so you cant
> safely run your tests in parallell on the same node. This is a reason
> I consider this to be a very dirty way to slip in the mock.

To follow up on myself. I hacked up something that almost fulfills my wishes:

You load this module that follows the inteface of an error_handler:



undefined_function(Mod, F, Args) ->
    case get(Mod) of
        undefined ->
            exit({undefined, Mod, F, Args});
        MockDict ->
            Fun = dict:fetch(F, MockDict),
            apply(Fun, Args)

undefined_lambda(_Mod, _Fun, _Args) ->

Second, I put this in my process to install the above error_handler
for this process:

init() ->
    Mock = dict:from_list([{eat, fun() -> yum end}]),
    put(banana, Mock),
    process_flag(error_handler, mock),

Whenever this process calls banana:eat(), it will get the atom 'yum'
back.  Completly process local.

YES! It is dirty!  The prettiest flowers grow in manure!

http://paste.lisp.org/display/61885 has more of the code and
experiment, at least until it goes away in a couple of hours.

More information about the erlang-questions mailing list