Replacing module with a stub for unit testing

pigmartian at pigmartian at
Sat May 23 09:00:15 EDT 2009


I'm working on a unit test framework for a module.  The module I'm
testing indirectly calls another module which is expensive to access
--- CDLLs whose functions access a database.

    test_MyModule --->MyModule--->IntermediateModule---

I want to create a stub of ExpensiveModule and have that be accessed
by IntermediateModule instead of the real version

    test_MyModule --->MyModule--->IntermediateModule---

I tried the following in my unittest:

    import ExpensiveModuleStub
    sys.modules['ExpensiveModule'] = ExpensiveModuleStub # Doesn't

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:  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?



More information about the Python-list mailing list