从我收集到的信息来看,使用 mock 时,您需要在修补时提供一个带点的名称。__name__
幸运的是,每个模块都可以访问一个包含模块名称的特殊模块级变量。使用这个,如果你想修补你的模块的本地变量,你应该能够做如下的事情:
import mock
import unittest
ook = lambda: "the ook"
class OokTest(unittest.TestCase):
def test_ook(self):
with mock.patch(__name__ + '.ook', return_value=None):
self.assertIsNone(ook())
self.assertEquals(ook(), "the ook")
# the patch decorator should work the same way, I just tend to use the
# context manager out of personal preference
@mock.patch(__name__ + '.ook', return_value=None)
def test_ook_2(self, mock_ook):
self.assertIsNone(ook())
假设您已将该文件保存为quicktest.py
,则单元测试会给出以下结果:
$ python -m unittest quicktest
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
当然,在你的包中from a.b import c
给你一个普通的变量c
,所以同样的机制应该可以工作。