Python mock multiple return values
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.
for multiple return values, we can use side_effect during patch initializing also and pass iterable to it
sample.py
def hello_world(): pass
test_sample.py
from unittest.mock import patchfrom sample import hello_world@patch('sample.hello_world', side_effect=[{'a': 1, 'b': 2}, {'a': 4, 'b': 5}])def test_first_test(self, hello_world_patched): assert hello_world() == {'a': 1, 'b': 2} assert hello_world() == {'a': 4, 'b': 5} assert hello_world_patched.call_count == 2
You can also use patch for multiple return values:
@patch('Function_to_be_patched', return_value=['a', 'b', 'c'])
Remember that if you are making use of more than one patch for a method then the order of it will look like this:
@patch('a')@patch('b')def test(mock_b, mock_a); pass
as you can see here, it will be reverted. First mentioned patch will be in the last position.