相关疑难解决方法(0)

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

我想了解如何@patch从导入的模块中获取函数.

这是我到目前为止的地方.

应用程序/ 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()
Run Code Online (Sandbox Code Playgroud)

应用程序/ my_module/__ init__.py:

def get_user_name():
  return "Unmocked User"
Run Code Online (Sandbox Code Playgroud)

测试/ 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()
Run Code Online (Sandbox Code Playgroud)

这并没有工作,我期望的那样."patched"模块只返回unmocked值get_user_name.如何从我导入到测试命名空间的其他包中模拟方法?

python unit-testing python-mock python-unittest

95
推荐指数
2
解决办法
5万
查看次数