[erlang-questions] Mocking in Erlang
Tue Jun 3 14:14:28 CEST 2008
> what is the typical way to handle the case where your module
> uses ibrowse say.
> is the best practice in testing just to not mock ibrowse? or
> do you typically just isolate the ibrowse calls in a small
> untested function and test everything else as normal? or is
> there some other trick I dont know about yet?
This is one of the reasons that I do not subscribe to the
"traditional" Erlang practise of writing interface modules that
hide message passing behind function calls. I like to expose the
message passing and have the message protocol /be/ the official
interface. Testing and mocking become very much easier.
However, when faced with existing applications that use the
interface module approach (such as, in your case, ibrowse) , I
resort to one of the following to perform mocking:
- define my own set of messages (usually a small subset of the
applications full functionality) and introduce a bridge process
- invert the dependency: avoid side-effects and don't call out to
ibrowse directly from the module that needs to be tested: have
it return lists of "ibrowse command" terms, and let the caller
pass these on to a dumb (untested) module that makes the actual
ibrowse calls given these terms
- create higher-order functions: always pass into the functions
of the module you want to test (that makes the ibrowse calls)
the functions it should use to make the calls. When there are
too many functions to make this practical, either pass in a
module, or pass in a single function whose first argument could
be the ibrowse function name...
- use parameterised modules, with the name of the module to be
used to make ibrowse calls being a parameter.
I am driven to adopt such approaches in order to achieve good
testability, but in my experience they turn out to be good
designs in themselves, with more flexibility and modularity.
More information about the erlang-questions