我有一个类在 __init__
以外的方法中初始化实例变量。该实例变量在 __init__
方法中进一步引用。
在下面的代码中,ProductionClass
是我正在测试的类。在 ProductionClass
中,__init__
调用方法 a_method
。方法 a_method
初始化实例变量 inst_var_2
。 inst_var_2
被 __init__
用来设置另一个实例变量 inst_var_3
。
class LibraryClass(object):
def __init__(self):
self.some_attrib = "some_attrib_value"
class ProductionClass(object):
def __init__(self, arg_one):
self.inst_var_1 = arg_one
self.a_method()
self.inst_var_3 = self.inst_var_2.some_attrib
def a_method(self):
self.inst_var_2 = LibraryClass()
import unittest
from unittest.mock import patch, MagicMock
class ProdTestCase(unittest.TestCase):
@patch.object(ProductionClass, 'a_method')
def test_init_method(self, mock_method):
instance = ProductionClass(1234)
self.assertEqual(1234, instance.inst_var_1)
mock_method.assert_called_once_with()
我正在尝试对 ProductionClass
的 __init__
方法进行单元测试,但我无法创建 ProductionClass
的实例,因为缺少实例变量 inst_var_2
。这是错误消息:
Traceback (most recent call last):
...
File "/... production_class.py", line 9, in __init__
self.inst_var_3 = self.inst_var_2.some_attrib
AttributeError: 'ProductionClass' object has no attribute 'inst_var_2'
我的问题是,在模拟 a_method
时是否可以对 __init__
方法进行单元测试。我想模拟 a_method
,因为我不希望该方法实例化 LibraryClass
。
最佳答案
您的问题本质上与:python mock - patching a method without obstructing implementation 相同.
由于您模拟了 a_method
,它不会设置 self.inst_var_2
。因此 __init__
不能成功。您必须在测试中考虑到这一点,但是,您仍然可以断言调用了模拟:
@patch.object(ProductionClass, 'a_method')
def test_init_method(self, mock_method):
with self.assertRaises(AttributeError):
ProductionClass(1234):
mock_method.assert_called_once_with()
I want to mock
a_method
because I don't want the method to instantiateLibraryClass
.
最好修补your_module.LibraryClass
,而不是a_method
。
关于python - 如何对在 __init__ 方法之外初始化的实例变量进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51862781/