Skip to main content
 首页 » 编程设计

Python:模拟我正在测试的模块正在使用的模块

2025年05月04日8zdz8207

我想模拟某个模块以测试使用该模块的一段代码。

也就是说,我有一个模块 my_module 我想测试一下。 my_module 导入外部模块 real_thing 并调用 real_thing.compute_something():

#my_module 
import real_thing 
def my_function(): 
    return real_thing.compute_something() 

我需要模拟 real_thing 以便在测试中它表现得像 fake_thing,这是我创建的一个模块:

#fake_thing 
def compute_something(): 
    return fake_value 

测试调用 my_module.my_function() 调用 real_thing.compute_something():

#test_my_module 
import my_module 
def test_my_function(): 
    assert_something(my_module.my_function()) 

我应该向测试代码添加什么,以便 my_function() 将在测试中调用 fake_thing.compute_something() 而不是 real_thing.compute_something() ?

我试图弄清楚如何使用 Mock 做到这一点, 但我没有。

请您参考如下方法:

简单地说不是吗?破解 sys.modules

#fake_thing.py 
def compute_something(): 
    return 'fake_value' 
 
#real_thing.py 
def compute_something(): 
    return 'real_value' 
 
#my_module.py 
import real_thing 
def my_function(): 
    return real_thing.compute_something() 
 
#test_my_module.py 
import sys 
 
def test_my_function(): 
    import fake_thing 
    sys.modules['real_thing'] = fake_thing 
    import my_module 
    print my_module.my_function() 
 
test_my_function() 

输出:'fake_value'