模拟函数中的实例方法调用

2024-05-28 23:10:36 发布

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

我现在有了第一次用python创建unittest套件来编写测试的实际经验,我的mock框架遇到了问题

目前,我有一个函数有这样一行:

def data_function():
    *Some code*
    with AccountDBConnection(account_id) as adb: # Pulling data
        data = adb.get_query_results(query)
    *Some more code*

我试图测试函数get_query_results是否被正确调用。在我的测试中,我尝试这样测试:

@patch('package.module_that_defines_data_function.AccountDBConnection')
def test_data_function(self, mock_AccountDBConnection):
    *Other assertions*
    mock_AccountDBConnection.get_query_results.assert_called_once_with(ANY)
    *more assertions*

不幸的是,每当我尝试运行这个测试时,我都会得到一个断言错误,声明get_query_results从未被调用。它当然被称为,我不能让它认识到这一点。我认为这是因为该方法是在函数中创建的对象的实例上调用的,但是我不知道如何让mock识别。有人有什么建议吗

非常感谢


Tags: 函数datagetdefmorewithcodefunction

热门问题