对于 test_foo, 您没有正确使用补丁。您应该像这样使用它:
class TestFoo(TestCase):
@patch.object(T1, 'foo', MagicMock(return_value='patched'))
def test_foo(self):
foo = T1().get_foo()
self.assertEqual('patched', foo)
这给了我:
nosetests test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
现在,第二个示例不起作用,因为您导入了bar函数(获取对其的引用),然后尝试对其进行模拟。模拟某些内容时,您无法更改变量的内容(对原始函数的引用)。要解决此问题,您应该使用@falsetru建议的方法,例如:
from unittest import TestCase
import unittest
from mock import patch
import spike
class TestFoo(TestCase):
@patch('spike.bar')
def test_bar(self, mock_obj):
mock_obj.return_value = 'patched'
value = spike.bar()
self.assertEqual('patched', value)
if __name__ == "__main__":
unittest.main()
这给了我:
python test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
但是当我尝试用鼻子跑它时,我得到:
nosetests test_spike.py
F
======================================================================
FAIL: test_bar (src.test_spike.TestFoo)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/zilva/envs/test/local/lib/python2.7/site-packages/mock/mock.py", line 1305, in patched
return func(*args, **keywargs)
File "/home/zilva/git/test/src/test_spike.py", line 11, in test_bar
self.assertEqual('patched', value)
AssertionError: 'patched' != 'bar'
----------------------------------------------------------------------
Ran 1 test in 0.001s
Failed (failures=1)
发生这种情况是因为我没有在正确的位置打补丁。我的目录结构是:
test/
└── src/
├── spike.py
├── test_spike.py
└── __init__.py
并且我从src目录运行测试,因此我应该使用项目根目录下的路径进行修补,例如:
@patch('src.spike.bar')
这会给我:
nosetests test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
或者如果我在测试目录中:
nosetests src/test_spike.py
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK