我想模拟某个模块以测试使用该模块的一段代码。
也就是说,我有一个模块 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'
关于Python:模拟我正在测试的模块正在使用的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12184911/