I have a python class with such a module:
xy.py
from a.b import ClassA class ClassB: def method_1(): a = ClassA() a.method2()
then I have ClassA defined as:
b.py
from c import ClassC class ClassA: def method2(): c = ClassC() c.method3()
Now in this code, when writing test for xy.py I want to mock.patch ClassC, is there a way to achieve that in python?
obviously I tried:
mock.patch('a.b.ClassA.ClassC')
and
mock.patch('a.b.c.ClassC')
None of these worked.
To mock an entire class you'll need to set the return_value to be a new instance of the class. @mock.
Rather than hacking on top of Python's import machinery, you can simply add the mocked module into sys. path , and have Python prefer it over the original module. Now, when the test suite is run, the mocked-lib subdirectory is prepended into sys. path and import A uses B from mocked-lib .
Once you patch a class, references to the class are completely replaced by the mock instance. mock. patch is usually used when you are testing something that creates a new instance of a class inside of the test.
Mock is a type, and patch is a context. So you are going to pass or receive Mock instances as parameters, and apply patch contexts to blocks of code. (Lowercase 'mock' is just the name of the package.) Tests and test classes are often decorated with calls to patch.
You need to patch where ClassC
is located so that's ClassC
in b
:
mock.patch('b.ClassC')
Or, in other words, ClassC
is imported into module b
and so that's the scope in which ClassC
needs to be patched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With