繁体   English   中英

Monkey在模块中修补功能以进行单元测试

[英]Monkey patch a function in a module for unit testing

我在调用从另一个模块导入的另一个方法的模块中有以下方法:

def imported_function():
    do_unnecessary_things_for_unittest()

需要测试的实际方法,导入并使用上述功能:

from somewhere import imported_function

def function_to_be_tested():
    imported_function()
    do_something_more()
    return 42

内部呼叫和内部imported_function相关计算并不重要,他们是不是我想要测试,所以我只是想跳过他们,而测试function_to_be_tested的实际功能是什么。

因此,我试图在测试方法内部的某个地方修补模块,但没有运气。

def test_function_to_be_tested(self):
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True

问题是,如何在测试时修补模块的方法,以便在测试阶段不会调用它?

我认为最好使用Mock Library

所以你可以这样做:

from somewhere import imported_function

@patch(imported_function)
def test_function_to_be_tested(self, imported_function):
    imported_function.return_value = True
    #Your test

我认为对于单元测试,它比猴子补丁更好。

假设您有以下文件:

somewhere.py

def imported_function():
    return False

testme.py

from somewhere import imported_function

def function_to_be_tested():
    return imported_function()

testme.function_to_be_tested()调用将返回False


现在,诀窍是 testme 之前导入somewhere

import somewhere
somewhere.__dict__['imported_function'] = lambda : True

import testme
def test_function_to_be_tested():
    print testme.function_to_be_tested()

test_function_to_be_tested()

输出:

真正


或者,重新加载testme模块

import testme

def test_function_to_be_tested():
    print testme.function_to_be_tested()
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True
    print testme.function_to_be_tested()
    reload(testme)
    print testme.function_to_be_tested()

test_function_to_be_tested()

输出:



真正

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM