unittest mock 如何模拟被调用的方法

unittest mock how to mock a method being called

我想测试方法 a 调用方法 b。这些方法位于单独的文件中,不是 class 对象的一部分。

# file_a.py
from file_b import b

def a():
    b()
# file_b.py
def b():
    test
import unittest
from unittest import mock

from file_a import a

class MyTestCase(unittest.TestCase):
    @mock.patch('file_b.b')
    def test_b_called(self, mock):
        a()
        mock.assert_called()

if __name__ == "__main__":
    unittest.main()

失败 AssertionError: Expected 'b' to have been called.

有正确的方法吗?

当您将函数导入当前命名空间时,就像在您的示例中一样,需要在该命名空间中修补该函数。在您的情况下,您需要:

@mock.patch('file_a.b')

如果您已经完成导入并像这样使用,您将修补 file_b.b

import file_b
def a():
    file_b.b()