擅长:python、mysql、java
<p>据我所知,使用mock,您需要在修补时提供一个虚线名称。幸运的是,每个模块都可以访问一个特殊的模块级变量<code>__name__</code>,该变量包含模块的名称。使用此选项,如果要修补模块的本地变量,则<em>应该能够执行以下操作:</p>
<pre class="lang-py prettyprint-override"><code>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())
</code></pre>
<p>假设您已将该文件保存为<code>quicktest.py</code>,那么单元测试将给出以下结果:</p>
<pre class="lang-none prettyprint-override"><code>$ python -m unittest quicktest
..
----------------------------------------------------------------------
Ran 2 tests in 0.001s
OK
</code></pre>
<p>当然,<code>from a.b import c</code>在包中给了您一个简单的变量,所以同样的机制也应该起作用。</p>