导入依赖

In [5]:
from unittest.mock import patch

from module import call_func

错误的用法

In [6]:
def test_call_func():
    def mocked_funny_func():
        return "not funny at all"

    with patch("dependency.some_funny_func", mocked_funny_func):
        return_value = call_func()

    assert return_value == "not funny at all"
    print("pass")
In [7]:
test_call_func()
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
<ipython-input-7-cfc31d4d8831> in <module>()
----> 1 test_call_func()

<ipython-input-6-55327b276a3a> in test_call_func()
      6         return_value = call_func()
      7 
----> 8     assert return_value == "not funny at all"

AssertionError: 

正确的用法

In [10]:
def test_call_func():
    def mocked_funny_func():
        return "not funny at all"

    with patch("module.some_funny_func", mocked_funny_func):
        return_value = call_func()

    assert return_value == "not funny at all"
    print("pass")
In [11]:
test_call_func()
pass

解析原理

In [13]:
# 模拟 dependency.some_funny_func
dependency = {}
dependency["some_funny_func"] = "some_value"

# 模拟 module.some_funny_func
module = {}
module["some_funny_func"] = dependency["some_funny_func"]

# 模拟 mock
dependency["some_funny_func"] = "some_other_value"

# 查看结果
print(dependency["some_funny_func"])
print(module["some_funny_func"])
some_other_value
some_value