Harshit Agarwal
Harshit Agarwal

Reputation: 908

Fake subfunction in django UnitTest Case (Mocking)

def func_b(**kwargs):
    return something


def func_a(request,*args,**kwargs):
    //do something
    b = func_b(**kwargs)
    //do something
    return something

I am writing UnitTest for func_a but i want to fake the output of func_b using mocking or anything similar to mocking in django. means simply i just want to fake the output of func_b and always want to return some static value from func_b in Test case. Is there any way to do that ?

Upvotes: 4

Views: 235

Answers (1)

alecxe
alecxe

Reputation: 473893

You should use mock.patch and specify the return_value. Here's an example where we are patching the return value of func_b() to Fake value on the fly:

from mock import patch
import unittest


def func_b():
    return "Real value"


def func_a():
    return "The result of func_b is '%s'" % func_b()


class MyTestCase(unittest.TestCase):
    def test_fake_value(self):
        with patch('test.func_b', return_value="Fake value") as mock_function:
            self.assertEqual(func_a(), "The result of func_b is 'Fake value'")

UPD:

with patch.object(module_name, 'func_b') as mock_function:
    mock_function.return_value = "Fake value"
    self.assertEqual(func_a(), "The result of func_b is 'Fake value'")

Upvotes: 1

Related Questions