简体   繁体   English

Python模拟:带有patch和return_value的意外结果

[英]Python Mock: Unexpected result with patch and return_value

I'll post some code first so it's more clear. 我将首先发布一些代码,这样更清楚。

My class: 我的课:

from tools import get_knife, sharpen

class Banana(object):
    def chop(self):
        knife = get_knife()
        sharpen(knife)

My test: 我的测试:

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)

This test will fail because sharpen_mock wasn't called with the return_value of get_knife_mock. 该测试将失败,因为未使用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. 这是Python应用装饰器的标准方法。 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 http://www.voidspace.org.uk/python/mock/patch.html#nesting-patch-decorators

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么python mock.patch在使用第二个补丁参数vs return_value时工作方式不同? - Why does python mock.patch work differently when second patch argument is used vs return_value? python模拟方法返回模拟而不是return_value吗? - python mock on method returning mock rather than return_value? Python模拟 - return_value - 获得“真实”的返回值 - Python Mock - return_value - getting the “real” return value Python模拟获取地址而不是return_value - Python Mock getting address instead return_value 难以理解 Python 的 return_value 在以下示例中模拟 Class - Hard to understand return_value for Python Mock Class in the following example unittest.mock.patch 的(未记录的)return_value 参数如何工作? - How does the (undocumented) return_value argument for unittest.mock.patch work? reset_mock() 得到了一个意外的关键字参数“return_value”——为什么? - reset_mock() got an unexpected keyword argument 'return_value' — why? python mock side_effect 或 return_value 依赖于 call_count - python mock side_effect or return_value dependent on call_count unittest.Mock - 结合return_value和side_effect - unittest.Mock - Combining return_value and side_effect 为什么用 pytest-mock 模拟的方法不返回值? - Why mocked method with pytest-mock does not return_value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM