[英]Unable to patch object inside function
I am new in Python.我是 Python 新手。 I would like to write an unit test for the following function:
我想为以下函数编写单元测试:
from common.ds_factory import DSFactory
class MyClass:
def load(self, parsed_file_key):
ds = DSFactory.getDS()
...
Now I am unable to mock DSFactory
using @patch(my_class.DSFactory)
as I am using DSFactory
inside the function.现在我无法使用
@patch(my_class.DSFactory)
模拟DSFactory
因为我在函数内部使用DSFactory
。
You need to patch DSFactory
for module that uses it.您需要为使用它的模块修补
DSFactory
。 As mentioned in comments, assuming MyClass
is defined in file my_module.py
you patch it by using module name: @patch("my_module.DSFactory")
.如评论中所述,假设
MyClass
在文件my_module.py
定义,您可以使用模块名称对其进行修补: @patch("my_module.DSFactory")
。
There's a catch - your module has to be importable, so it requires you to create modules.有一个问题 - 您的模块必须是可导入的,因此它需要您创建模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.