您应该使用mock.patch
并指定return_value
. func_b()
这是一个示例,我们正在动态修补to的返回值Fake value
:
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'")
升级版:
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'")