Replacing module with a stub for unit testing

Ben Finney ben+python at benfinney.id.au
Sat May 23 09:27:51 EDT 2009


pigmartian at gmail.com writes:

> 
>     import ExpensiveModuleStub
>     sys.modules['ExpensiveModule'] = ExpensiveModuleStub # Doesn't
> work
> 
> But, import statements in the IntermediateModule still access the real
> ExpensiveModule, not the stub.
> 
> The examples I can find of creating and using Mock or Stub objects
> seem to all follow a pattern where the fake objects are passed in as
> arguments to the code being tested. For example, see the "Example
> Usage" section here: http://python-mock.sourceforge.net. But that
> doesn't work in my case as the module I'm testing doesn't directly use
> the module that I want to replace.
> 
> Can anybody suggest something?

The ‘MiniMock’ library <URL:http://pypi.python.org/pypi/MiniMock>
addresses this by mocking objects via namespace.

If you know the code under test will import ‘spam.eggs.beans’, import
that yourself in your unit test module, then mock the object with
‘minimock.mock('spam.eggs.beans')’. Whatever object was at that name
will be mocked (until ‘minimock.restore()’), and other code referring to
that name will get the mocked object.

-- 
 \     “When I turned two I was really anxious, because I'd doubled my |
  `\   age in a year. I thought, if this keeps up, by the time I'm six |
_o__)                                  I'll be ninety.” —Steven Wright |
Ben Finney



More information about the Python-list mailing list