Python 从 class 模拟一个未导入的方法

Python mock a method from a class that was not imported

举个例子,func_to_test_script.py

from module import ClassA

def func_to_test():
    instance_b = ClassA.method_a()
    foo = instance_b.method_b()

method_a returns class ClassB.

的实例

我想模拟方法 method_amethod_b 的调用,所以我这样做了

@mock.patch("func_to_test_script.ClassA", ClassAMock)
@mock.patch("func_to_test_script.ClassB", ClassBMock)
def test_func_to_test(self):
    # test

我可以使用 ClassA(在 func_to_test 的文件中导入)来执行此操作,但是使用 ClassB 我得到错误

AttributeError: <module 'module' from 'func_to_test_script.py'> does not have the attribute 'ClassB'

首先,它真的会失败,因为 ClassB 没有定义也没有导入 func_to_test_script.py。但即使是,也没有必要打补丁,因为它无论如何都不会生效。为什么?因为 ClassB 的实例将来自 ClassA 的响应,您已经模拟了它。

你能做的就是从 ClassA:

的 mock 中控制它
@mock.patch("func_to_test_script.ClassA")
def test_func_to_test(self, mock_class_a):
    mock_class_a.method_a.return_value.method_b.return_value = "value of foo"
    ...