[TIP] Mock objects and hierarchical visitor pattern

Stefano Masini stefano.masini at pragma2000.com
Thu Jun 7 14:25:27 PDT 2007


I have a question for you gurus. I hope to be clear and concise.
Say that I have a tree of objects like Tree() containing a list of
Branch() each containing a list of Leaf().
Now, say that by using a hierarchical visitor pattern I have an
algorithm that traverses the tree and calls functions liks
processTree(tree), processBranch(branch) and processLeaf(leaf). These
functions are the System Under Test, and since they place calls to an
outside library, I decide to use mock objects to simulate the library.

So, for example, starting from the deepest level (leaves) I write some
tests for processLeaf(leaf) that prepare some leaf object, pass it to
the processLeaf() function, but before that I set up my mocks and
write expectations for them.
Ok. Everything is fine.

Now let's go up one level, and test processBranch(branch).
I would like to follow the same approach, i.e. prepare a branch, set
the mock expectations and call processBranch(). But this time, since a
branch is made of leaves, the functions processBranch() will call
several times the function processLeaf(). This is very unconvenient,
because it forces me to define a whole bunch of expectations on the
mock objects, even for mock leaves, that I don't care much about,
since processLeaf() has already been tested.

How can I make my life easier?

Thanks a lot.

More information about the testing-in-python mailing list