python - 使用模拟测试构造函数

标签 python mocking

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

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)

关于python - 使用模拟测试构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42674971/

相关文章:

python - Assert_called_once_with 需要检查调用中的实例是否具有相同的信息

java - stub 方法时收到 InvalidUseOfMatchersException

python - 如何通过组合 pandas 数据框中的两行来创建列

Python:如何查询对象列表?

java - 如何在 Clojure 中模拟 Java 对象

python - 如何模拟/修补整个类(class)?

python - 如何为绘制的对象(例如drawLine)制作透明背景?

python - 根据另一个数据框的匹配结果在数据框中创建新列

python - Python 不变量

javascript - Jasmine :这是 returnValue 和 callFake 之间的唯一区别吗?