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

标签 python unit-testing mocking

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

也就是说,我有一个模块 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/

相关文章:

XCode 单元测试 - 在范围内找不到 View Controller

c# - 在 C# 中模拟局部变量

c# - 如何对返回 void 的方法进行单元测试?

python - 错误 : Could not build wheels for opencv-python which > use PEP 517 and cannot be installed directly

java - stub 和模拟时的区别

reactjs - 如何在单元测试期间更新 React Component props?

java - ServletFileUpload.parseRequest() 为 MockMultipartHttpServletRequest 返回一个空列表

python - 如何从另一个文件调用函数?

python - 为什么我在使用 Fabric python 库时会收到低级套接字错误?

python - 如何在 numpy ndarray 中找到最频繁的字符串元素?