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 mockery or something similar to django's mockery. it means that I just want to fake the output of func_b and always want to return a static value from func_b in the test case. Is there any way to do this?

+4
source share
1 answer

You should use mock.patch and specify return_value . Here is an example where we correct 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'") 
+1
source

All Articles