将Mock.side_effect用于实例方法

时间:2015-09-11 18:27:54

标签: python

我正在尝试使用side_effect在Python中模拟实例方法。我希望/期望我的副作用是用一个初始的“自我”参数调用的,我可以用它来确定返回值。

所以我有这样的事情:

import mock

class TestCases(unittest.TestCase):

  @mock.patch('Item.exists')
  def test_foo(self, mock_item_exists):

    def item_exists_side_effect(*args, **kwargs):
      # I expect args[0] here to be supplied and to refer to the item
      _self = args[0]
      return _self.name == 'bar'

    mock_item_exists.side_effect = item_exists_side_effect

    ...

但是,当调用Item.exists()时,我最终会在我的副作用函数中使用空args列表。

这是预期的吗?我做错了吗?

1 个答案:

答案 0 :(得分:2)

看起来这就是原因:

Why does mock ignore the instance/object passed to a mocked out method when it is called?

即。通过调用mock.patch,我将实例方法转换为类方法。

相关问题