使用模拟测试构造函数



我需要测试我的班级构造函数调用某些方法

class ProductionClass:
   def __init__(self):
       self.something(1, 2, 3)
   def method(self):
       self.something(1, 2, 3)
   def something(self, a, b, c):
       pass 

此课程来自'Unittest.mock - 入门'。正如在那里写的那样,我可以确保"方法"称为"某物"如下。

real = ProductionClass()
real.something = MagicMock()
real.method()
real.something.assert_called_once_with(1, 2, 3)

但是如何测试构造函数?

您可以使用补丁程序(检查它的文档https://docs.python.org/dev/library/unittest.mock.html)对象的实例,something方法被调用一次,并与所需的参数调用。例如,在您的示例中,这将是这样的:

from unittest.mock import MagicMock, patch
from your_module import ProductionClass
@patch('your_module.ProductionClass.something')
def test_constructor(something_mock):
    real = ProductionClass()
    assert something_mock.call_count == 1
    assert something_mock.called_with(1,2,3)