未记录模拟对象的初始化

2024-06-16 17:13:30 发布

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

我试图测试类的构造函数的成功调用,但它没有被记录在我的模拟对象中。我分别使用pytestpytest-mock库进行单元测试和模拟

假设我在模块transaction.py的包cryptocurrency中有以下类:

class Transaction:
    def __init__(self, test):
        self.test = test

在模块test_transaction.py中的另一个包tests中进行以下测试:

def test_constructor(mocker):
    mock_transaction = mocker.patch('cryptocurrency.transaction.Transaction', 
        autospec=True)
    Transaction('123')
    mock_transaction.assert_called_once()

为什么测试失败并显示以下消息:

AssertionError: Expected 'Transaction' to have been called once. Called 0 times.

模拟对象不应该监听类实例的初始化并记录它吗

编辑:我得到了这个问题的答案,但我有另一个类似的情况,仍然不工作。假设类Transaction也有以下方法:

@classmethod
def new_transaction(cls, test)
    return cls(test)

测试是:

def test_new_transaction(mocker):
    mock_transaction = mocker.patch('cryptocurrency.transaction.Transaction', 
        autospec=True)
    Transaction.new_transaction('123')
    mock_transaction.assert_called_once()

我不能让它工作。我已经试着把补丁改成__name__ + 'Transaction'了,但还是不起作用。我觉得我的初始解决方案应该是正确的,因为即使测试引用了某个Transaction导入,new_transaction()方法也会在cryptocurrency.transaction.Transaction处与原始的Transactiion交互


Tags: 模块对象pytestnewpytestdef记录