使用m测试构造函数

2024-04-29 13:46:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要测试类的构造函数是否调用了某些方法

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-getting started”。正如上面写的,我可以确保“method”调用“something”如下。

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

但是如何对构造器进行同样的测试呢?


Tags: 方法selfinitdefpassunittestmockreal
1条回答
网友
1楼 · 发布于 2024-04-29 13:46:51

您可以使用patch(检查文档中的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)

相关问题 更多 >