我需要测试我的类的构造函数调用一些方法
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
Run Code Online (Sandbox Code Playgroud)
这个课程来自'unittest.mock - 入门'.正如在那里写的,我可以确保'方法'被称为'某事'如下.
real = ProductionClass()
real.something = MagicMock()
real.method()
real.something.assert_called_once_with(1, 2, 3)
Run Code Online (Sandbox Code Playgroud)
但是如何为构造函数测试相同的呢?
您可以使用补丁(请查看文档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)
Run Code Online (Sandbox Code Playgroud)