I'm trying to implement some unittests to validate a method that contains a for loop. This method receives a list of items and for each one of them it executes a function foo() with the item as a parameter.
Does anyone know how can I mock the foo() function to dynamically provide the mocked returned value depending on the element provided as input?
The methods:
def foo(i):
if i == 'this':
return 'a'
else:
return 'b'
def bar(items):
results = []
for item in items:
results.append(foo(item))
return results
The unittest:
from unittest import TestCase
from mock import patch
class TestCaseBar(TestCase):
@patch('my_module.foo')
def test_bar(self, mock_foo):
mock_foo.return_value = 'dummy' # I would like to dinamically mock this.
items = ['this', 'that']
result = bar(items)
self.assertEqual(result, ['a', 'b'])
self.assertTrue(mock_foo.call_count, 2)
Thanks in advance for your answers.
foofunction (which will look like the example you show) and use it as a mock.mock_foo.return_valueor tomock_foodirectly.@patch('my_module.foo, my_foo), ifmy_foois your function. Usingside_effectas shown in the answer is another possibility.