python 模拟 : Unexpected result with patch and return_value

标签 python mocking

我会先贴出一些代码,这样更清楚。

我的类(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/

相关文章:

Python 程序可能导致文件系统错误

python - 创建事件过滤器

Python 补丁装饰器溢出到其他方法中

python - 使用 Pytest 和 Mock 测试查询数据库的 View

android - 模拟每个 { ... } block 内的缺失调用

c# - 如何使用 NSubstitue 框架从 Controller 类模拟基方法

java - 使mockito强制方法在进程完成之前返回其值

python - 读取图像灰度opencv 3.0.0-dev

python - 为什么在 for 循环中使用 PIL 的 Image.paste 时出现图像重叠问题?

Python 多处理 : shared memory and pickle issue