[erlang-questions] how: Mock processes in a test setup

Christian S <>
Thu Apr 3 07:43:50 CEST 2008

On Thu, Apr 3, 2008 at 2:03 AM, Zvi <> wrote:
>  I also interested in this subject. I'm not an expert, but I think that
>  standard way to implement mockups/stubs/simulations in Erlang it's using
>  callback modules, especially in OTP.
>  I.e. suppose you have gen_fsm process controlling some fancy hardware. The
>  hardware is not available yet, so you write mockup gen_fsm callback module:
>  fancy_hw_sim . When actual hardware is available, you write   fance_hw_real
>  callback module.  Then you either put callback name into define or choose it
>  at runtime at start / start_link .

Oh yeah. Thats one way to make a mockup process, but it takes quite a
lot of code, especially if you want to check that the mockup receives
messages in the expected order. The benefit of having testing easy is
hopefully I write more tests.

After a night's sleep, these are the ideas/thoughts:

Mock = mock:new(),
mock:expect(Mock, fun ({message, _Pattern}) -> ok end),
mock:expect(Mock, fun ({side_effect, Process}) -> Process ! reply, ok end),
%% ... code to set up the scenario that involves the process to test,
%% which will make the tested process message my Mocked process ...
ok = mock:assertExpectation(Mock)

This is not bad. A bit verbose but acceptable. Maybe it would be good
to have internal state in the mock process and pass that to the funs.

Java's EasyMock has some features for expecting
one-or-more/at-least-N/at-most-N/between-Min-and-Max method calls.
Those might be important for not ending up with tests that are too
fragile (so the test doesnt depend too much on implementation details,
but only high level behavior). I imagine that for the erlang
programmer it is more important to be able to handle some messages in
arbitrary order.

I noticed how similar this seems to a regexp, a regexp on messages
rather than characters.

More information about the erlang-questions mailing list