imagine you have a module
from module.my_module import Foo
def my_function():
foo = Foo()
return whatewer_can_happen(foo)
that you want to test like this
class TestFoo:
def __init__():
pass
def dont_care():
return 9
def test_something():
with mock.patch('tested_module.Foo') as mocked_class:
mocked_class.side_effect = lambda *args: TestFoo(*args)
assert tested_module.my_function() == 'not important'
essentially as if you wanted to inject the TestFoo in place of Foo
(example wont work ofc, only for illustration)
How to mock the Foo
class in the tested module without changing the tested code? If it is not possible, why - how are classes in python so different to functions that mocking them is not possible?
I am not looking for ways to do it differently(factory function/mocking only class functions directly etc)
It would in some cases just be helpful (and more readable) to be able to write mock classes and inject them for use into the tested module
Copyright Notice:Content Author:「Derte Trdelnik」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/64318831/mocking-class-by-replacing-it