【问题标题】:How to unit test instance variables initialized outside __init__ method如何对在 __init__ 方法之外初始化的实例变量进行单元测试
【发布时间】:2018-08-15 16:34:42
【问题描述】:

我有一个在__init__ 以外的方法中初始化实例变量的类。该实例变量在__init__ 方法中被进一步引用。

在下面的代码中,ProductionClass 是我正在测试的类。在ProductionClass 中,__init__ 调用方法a_method。方法a_method 初始化实例变量inst_var_2inst_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__ 方法进行单元测试,但由于缺少实例变量inst_var_2,我无法创建ProductionClass 的实例。这是错误消息:

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 python-unittest


    【解决方案1】:

    您的问题与: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()
    

    我想模拟a_method,因为我不希望该方法实例化LibraryClass

    最好修补your_module.LibraryClass,而不是a_method

    【讨论】:

    • 感谢您提出一种调用assert_called_once_with 的方法,即使ProductionClass 的实例化失败。您还建议我模拟 LibraryClass 而不是 a_method 非常有帮助。有时,当我从我正在调用的方法中模拟出所有方法调用时,我往往会陷入采用“纯粹”的方法......
    • 您问题的链接也很有帮助。我将尝试在我的测试中应用其中列出的一些技术。
    猜你喜欢
    • 1970-01-01
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2016-02-13
    • 1970-01-01
    相关资源
    最近更新 更多