Reputation: 426
The question is in context of unit testing. I have created an instance of the class I am testing, and trying to test one of its methods. The method uses data it gets from different class defined in separate module. I am going to mock that module. How I can access my instance's name space - I have to do it before running the method I am testing, to mock module which contain definition of the class my method is getting data from?
Upvotes: 0
Views: 322
Reputation: 208425
I am going to create an example here which I think parallels what you are trying to do.
Say you have some class that we'll call Data
that is defined in the module foo
. The foo
module imports bar
and a method of foo.Data
calls bar.get_data()
to populate itself.
You want to create a module test
that will create an instance of foo.Data
, but instead of using the actual module bar
you want that instance to use a mocked version of this.
You can set this up by importing foo
from your test module, and then rebinding foo.bar
to your mocked version of the module.
Here is an example of how this might look:
bar.py:
def get_data():
return 'bar'
foo.py:
import bar
class Data(object):
def __init__(self):
self.val = bar.get_data()
if __name__ == '__main__':
d = Data()
print d.val # prints 'bar'
test.py:
import foo
class bar_mock(object):
@staticmethod
def get_data():
return 'test'
if __name__ == '__main__':
foo.bar = bar_mock
d = foo.Data()
print d.val # prints 'test'
Although this will get you by for a simple test case, you are probably better off looking into a mocking library to handle this for you.
Upvotes: 2