I tried to implement a mock in my unit tests but it is never called, even though it should.
tests.py
from mock import patch
class MyTest(TestCase):
def test_add(self):
name = 'Test'
with patch('my_module.my_file.my_function') as add_method:
m = MyModel(name=name)
m.save()
add_method.assert_called_with(name=name)
models.py
from my_module.my_file import my_function
class MyModel(Model):
name = CharField(max_length=12)
def save(self, *args, **kwargs):
my_function(self.name)
super(MyModel, self).save(*args, **kwargs)
my_file.py
def my_function(name):
# Processing...
When I run the unit test, it just tells me the mock has not been called, though it should be, I know the script works fine. Do you have any idea/advice for me?
When models
is imported, it runs from my_module.my_file import my_function
, which is not mocked yet. When you run your test case, the my_function
name in the models
module is already bound to the real function: patching my_files
has no effect.
What you need is to patch models.my_function
:
with patch('models.my_function') as add_method:
m = MyModel(name=name)
m.save()
An alternative would be to patch my_file.my_function
at models
import time.
See where to patch documentation.