[erlang-questions] Mocking processes for testing

Ben Butler-Cole benbutlercole@REDACTED
Mon Aug 13 00:36:59 CEST 2007


Michael

I have written a test library with facilities for creating mocks and stubs. I just wrote it for my own use and it needs some work before it's publishable, but I would be happy to share what I have with you.

It allows the creating of mock processes (which expect messages to be sent to them) and stub ones (which silently accept any message). Either type can be created as an anonymous or as a registered process.

Code that uses the library looks like this:

    should_feed_marmosets_at_break_of_day() ->
        stub(cat),
        M = mock({expect, {food, weevil}}),
        Keeper = keeper:new([M]),
        Keeper ! wake_up.

    should_kick_cat_at_break_of_day() ->
        mock(cat, {expect, kick}),
        Keeper = keeper:new([]),
        Keeper ! wake_up.

Where the keeper's code contains something like this:

    loop(Marmosets) ->
        receive
            wake_up ->
                cat ! kick,
                lists:foreach(fun(M) -> M ! weevil end, Marmosets),
                loop(Marmosets)
            % ...
        end.

The cat is modeled as a registered process just to show what is possible. It is also possible to create expectations on existing mocks (by sending them messages) when dependencies are more complicated. It's not currently integrated with EUnit (or any other proper testing framework), but probably should be.

Let me know if you are interested. If several people would like to use it I'll publish it somewhere.

Ben






More information about the erlang-questions mailing list