在调用从另一个模块导入的另一个方法的模块中,我有以下方法:
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
导入的函数中的内部调用和相关计算并不重要,它们不是我要测试的内容,所以我只想在测试实际的函数时跳过它们。
因此,我试图在测试方法中的某个地方对名为的模块进行猴子修补,但没有成功。
def test_function_to_be_tested(self):
import somewhere
somewhere.__dict__['imported_function'] = lambda : True
问题是,如何在测试时对模块的方法进行修补,以便在测试阶段不会调用它?
假设您有以下文件:
某处。py
测试时间.py
对
testme.function_to_be_tested()
的调用将返回False
。现在,诀窍是在
testme
之前导入somewhere
:输出:
或者,重新加载
testme
模块输出:
我想最好用Mock Library
所以你可以这样做:
我认为对于单元测试来说,它比猴子补丁要好。
相关问题 更多 >
编程相关推荐