I have a Python class structure similar to the following example:
class Foo:
def start(self):
# do something
class FooBar(Foo):
def __init__(self, param):
self.param = param
def run(self):
# do something else
class ProductionClass:
def use_foobar(self):
foo = FooBar("string")
foo.start()
Now I want to write a test in which the start
method on FooBar
(inherited from Foo
) is mocked so that the run
method defined directly in FooBar
is called instead.
I tried it this way:
def test_something(self):
self.foobar_patcher = patch.object(FooBar, 'start', side_effect=self.mock_start)
self.foobar_patcher.start()
ProductionClass().use_foobar()
def mock_start(self):
the_production_class_instance.run()
In this example, the_production_class_instance
is meant to be the instance of FooBar where the start()
method was called on, but I can’t seem to find a way where to get this instance. The instance is created inside ProductionClass().use_foobar()
and discarded after use, so there is no real way to access it from the outside.
Is there a way to achieve this with unittest?