[Fixed]-Unit-testing Python: Mocking function calls inside function

24👍

You can use @mock.patch decorator to mock f2() method in your unittests.

import mock
import some_module
from django.test import TestCase

def mocked_f2(**kargs):
    return 'Hey'

class YourTestCase(TestCase):

    @mock.patch('some_module.f2', side_effect=mocked_f2)
    def test_case(self, mocked):
        print some_module.f2()  # will print: 'Hey'

In this case each time you call f2() in your code, mocked_f2 will be called.

2👍

django supplies some scaffolding for testing – see the docs

as for f2() – you can use fixtures to set up a db. Alternatively use mock to supply a dummy db connection.

Leave a comment