[Django]-How do I mock a component in my django application that reaches to an external service?

3👍

If you had a python module animals.py that had this:

def create_animals(candidate):
    if ExternalService.get_candidate_validity(candidate):
         print('Things are good, go ahead')
         #creates the animal objects etc....

You would mock it out this way in test_animals.py

from mock import MagicMock  # or import mock from stdlib unittest in python 3

def test_create_animals():
    from path.to.animals import ExternalService, create_animals
    ExternalService.get_candidate_validity = MagicMock(return_value=True)
    animals = create_animals('foo')
    ExternalService.get_candidate_validity.assert_called_with('foo')

It is a best practice in unit testing to mock out all external services somehow so you’re testing the unit, ie the function being tested, and nothing else.

Another way to do this is to use the patch functionality in the standard unit testing library.

https://docs.python.org/3/library/unittest.mock.html#attaching-mocks-as-attributes

>>> with patch('animals.ExternalService') as MockClass:
...     MockClass.get_candidate_validity.return_value = 'foo'

Leave a comment