Posted on Wednesday, 8th October 2008 by charpi

In my previous post, I wrote a test to specify a lazy
mock. In my mind, a lazy mock consists to replace the implementation
of one module by another one at runtime.

Here is the implementation of the lazy mock test


-export([replace_module /2]).

replace_module (Module, Mock_module) ->
    uninstall (Module),
    {ok, Binary} = file: read_file (code: which (Mock_module)),
    File_name = atom_to_list (Module) ++ ".erl",
    code: load_binary(Module, File_name, Binary),

uninstall (Module) ->
    code: purge (Module),
    code: delete (Module).

The tricky thing is that your mock module must not be a valid
erlang beam file. The code_loader use the beam file name to locate the
code load but the VM expected that the module declaration in the file
got the same name than the file.
In order to use my implementation of the lazy mock your mock
module must have the same module declaration than the real
Here is the content of the source file my_mock_module.erl:


-export([who /0]).

who () ->
    "I'm the mocked code".

Tags: ,
Posted in Uncategorized | Comments (1,859)

Comments are closed.