我一直在用这样的小模型将头撞在墙上:
这是树:
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'
这意味着模拟无法正常工作。我似乎无法弄清楚自己出了什么问题。
在file_b中,您希望在“ init”中传递2个参数def __init__(self, a, b):
但是在file_a中,当您为类bar创建对象时,没有传递任何参数bar_inst = bar()
这就是为什么您看到错误TypeError: __init__() missing 2 required positional arguments: 'a' and 'b'
您要做两件事:
def __init__(self, a, b):
中删除参数a和b