我一直在用这样的小模型把头撞在墙上:
这是树:
src
├── __init__.py
├── file_a.py
├── file_b.py
test
├── test_a.py
在 file_a 中:
class qaz(object):
def __init__(self):
print("\n\nin qaz")
def exec_bar(self):
bar_inst = bar()
bar_inst.execute("a", "b")
在 file_b 中:
class bar(object):
def __init__(self, a, b):
print("\n\nin bar")
def execute(self, c, d):
print("\n\nin bar -> execute")
所以,我想模拟bar
,以便我可以a
毫无问题地进行测试。
在 test_a 中:
from unittest.mock import patch, MagicMock
from src.file_a import qaz
from src.file_b import bar
class BarTester(unittest.TestCase):
@patch('src.file_b.bar')
def test_bar(self, mock_bar):
bar_inst = MagicMock()
bar_inst.execute.return_value = None
mock_bar.return_value = bar_inst
q = qaz()
q.exec_bar()
每次都会失败,如下所示:
TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'
这意味着模拟不起作用。我似乎无法弄清楚我做错了什么。