【发布时间】:2021-04-02 22:00:04
【问题描述】:
我想模拟一个类方法的输出,该输出由不同模块中定义的函数调用。例如:
class_module.py
class my_class:
def __init__(self, user):
self.user = user
def my_method(self):
return [1,2,3]
def other_methods(self):
other_func(self.user)
return "something I do not really want to mock"
function_module.py
from class_module import my_class
def my_fun():
user = "me"
foo = my_class(user)
foo.other_methods()
return foo.my_method()
test.py
@patch("function_module.my_class")
def test_my_fun(class_mock):
class_mock.return_value.my_method.return_value = []
bar = my_fun()
assert bar == []
但是,我收到一个AssertionError 说[1,2,3] != []。所以我想模拟永远不会发生在我想要的方法上。有人可以解释怎么做吗?为什么会这样?
编辑
实际上,显示的实现不起作用,因为测试正在启动一个完全独立的过程。因此,不能模拟任何函数。对不起,我的误解
【问题讨论】:
-
您不修补单个方法,替换类
@patch("function_module.my_class")然后查看例如stackoverflow.com/a/38199345/3001761. -
谢谢@jonrsharpe,我尝试了您提供的其他答案。但是,我仍然遇到同样的问题。我更新了我的问题,使其与我的代码更相似
-
你的代码适合我,测试在本地通过。
标签: python testing pytest python-unittest pytest-mock