我会先贴出一些代码,这样更清楚。
我的类(class):
from tools import get_knife, sharpen
class Banana(object):
def chop(self):
knife = get_knife()
sharpen(knife)
我的测试:
from mock import patch, sentinel
from banana import Banana
class TestBanana(unittest.TestCase):
@patch('banana.get_knife')
@patch('banana.sharpen')
def test_chop(self, get_knife_mock, sharpen_mock):
get_knife_mock.return_value = sentinel.knife
Banana().chop()
sharpen_mock.assert_called_with(sentinel.knife)
此测试将失败,因为未使用 get_knife_mock 的 return_value 调用 sharpen_mock。
最佳答案
Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.
http://www.voidspace.org.uk/python/mock/patch.html#nesting-patch-decorators
关于 python 模拟 : Unexpected result with patch and return_value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5614976/