Python mock multiple return values

后端 未结 1 1307
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 19:02

I am using pythons mock.patch and would like to change the return value for each call. Here is the caveat: the function being patched has no inputs, so I can not change the

相关标签:
1条回答
  • 2020-11-30 19:45

    You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

    >>> from unittest.mock import Mock
    >>> m = Mock()
    >>> m.side_effect = ['foo', 'bar', 'baz']
    >>> m()
    'foo'
    >>> m()
    'bar'
    >>> m()
    'baz'
    

    Quoting the Mock() documentation:

    If side_effect is an iterable then each call to the mock will return the next value from the iterable.

    0 讨论(0)
提交回复
热议问题