我有一个模块A
,其中包含以下两个函数:
def my_func():
my_dict = {"key1":100, "key2": 100}
send_result(dicts=my_dict)
def send_result(dicts):
print(dicts)
我编写了如下单元测试用例:
from unittest.mock import MagicMock
import A
def test_send_results(self, dicts):
self.assertGreater(len(dicts), 0)
def test_my_func(self):
A.send_result = MagicMock(wraps=self.test_send_results)
A.my_func()
当我运行单元测试用例时,尽管字典包含以下值,但我得到以下错误:
TypeError: test_send_results() missing 1 required positional argument: 'dicts'
正如 Anthony 所建议的,使用 patch.object。下面举一个例子:
import unittest
from unittest import mock
import A
class MyTestClass(unittest.TestCase):
def test_send_results(self, dicts):
self.assertGreater(len(dicts), 0)
@mock.patch.object(self, 'test_send_results')
def test_my_func(self, mock_func):
mock_func.return_value = 'something'
A.my_func()