Python 从导入的模块中模拟一个函数

标签 python unit-testing python-unittest python-mock

我想了解如何@patch导入模块中的函数。

这是我目前为止的地方。

app/mocking.py:

from app.my_module import get_user_name

def test_method():
  return get_user_name()

if __name__ == "__main__":
  print "Starting Program..."
  test_method()

app/my_module/__init__.py:

def get_user_name():
  return "Unmocked User"

test/mock-test.py:

import unittest
from app.mocking import test_method 

def mock_get_user():
  return "Mocked This Silly"

@patch('app.my_module.get_user_name')
class MockingTestTestCase(unittest.TestCase):

  def test_mock_stubs(self, mock_method):
    mock_method.return_value = 'Mocked This Silly')
    ret = test_method()
    self.assertEqual(ret, 'Mocked This Silly')

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

这确实按我的预期工作。 “已修补”模块仅返回 get_user_name 的未模拟值。如何模拟要导入到正在测试的命名空间的其他包中的方法?

最佳答案

当您使用 unittest.mock 包中的 patch 装饰器时,您是在在正在测试的命名空间中修补它(在本例是 app.mocking.get_user_name),而不是导入函数的命名空间(本例中是 app.my_module.get_user_name)。

要执行您使用 @patch 描述的操作,请尝试以下操作:

from mock import patch
from app.mocking import test_method 

class MockingTestTestCase(unittest.TestCase):
    
    @patch('app.mocking.get_user_name')
    def test_mock_stubs(self, test_patch):
        test_patch.return_value = 'Mocked This Silly'
        ret = test_method()
        self.assertEqual(ret, 'Mocked This Silly')

标准库文档包括一个有用的 section描述这个。

关于Python 从导入的模块中模拟一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16134281/

相关文章:

c# - 是否有必要在单元测试中启用可空上下文?

unit-testing - 如何在包含命名空间的 TFS Build 中使用 TestCaseFilter 排除单元测试

python - 如何将 per-env Tox deps 与 Pip 需求文件结合起来?

python - AssertListEqual 不改变类 __eq__ 方法

python - 在python中对字母数字字典键进行排序

python - Jinja2 中的 zip(list1, list2)?

python [:-1] vs remove

python - 如何在google-colaboratory上永久上传数据?

unit-testing - 错误 : Action may not be undefined in async action testing in Redux app with nock and mock-store

python-2.7 - Python 模拟 Autospec 与 Spec