如何在Python中模拟另一个函数中的函数?

2024-05-08 13:56:06 发布

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

我想模拟另一个函数中的函数,如下所示:

def parent_function():
    def child_function():
        # mock this function
        return something_1

    child_function()  # calling the child function and doing other things 
    return something_2

以下是我试图嘲笑它的方式:

@patch('package.parent_function.child_function')
def test_some_method(self, mocked_function):
    # doing testing

它抛出了以下错误:

AttributeError: <function parent_function at 0x7f7d46a2d170> does not have the attribute 'child_function'

我做错了什么?我怎样才能解决这个问题

另外,请不要建议我修改主代码,因为我不允许这样做,我只能做测试


Tags: andthe函数childreturndeffunctionthis