我正在尝试为类的编写单元测试__init__
:
def __init__(self, buildNum, configFile = "configfile.txt"):
super(DevBuild, self).__init__(buildNum, configFile)
if configFile == "configfile.txt":
self.config.MakeDevBuild()
config 属性由 super 的__init__
. 我正在使用mock,我希望 config 属性是一个模拟对象。但是,我一直无法弄清楚如何真正做到这一点。这是我能想到的最好的测试:
def test_init(self):
with patch('DevBuild.super', create=True) as mock_super:
mock_MakeDevBuild = MagicMock()
mock_super.return_value.config.MakeDevBuild = mock_MakeDevBuild
# Test with manual configuration
self.testBuild = DevBuild("42", "devconfigfile.txt")
self.assertFalse(mock_MakeDevBuild.called)
# Test with automated configuration
self.testBuild = DevBuild("42")
mock_MakeDevBuild.assert_called_once_with()
但是,这不起作用——我收到一个错误:
Error
Traceback (most recent call last):
File "/Users/khagler/Projects/BuildClass/BuildClass/test_devBuild.py", line 17, in test_init
self.testBuild = DevBuild("42")
File "/Users/khagler/Projects/BuildClass/BuildClass/DevBuild.py", line 39, in __init__
self.config.MakeDevBuild()
AttributeError: 'DevBuild' object has no attribute 'config'
显然我没有正确设置配置属性,但我不知道我应该在哪里设置它。或者就此而言,如果我想要做的甚至是可能的。谁能告诉我我需要做什么才能完成这项工作?