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

时间:2012-08-29 19:09:38

标签: python unit-testing mocking

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

也就是说,我有一个我想测试的模块my_modulemy_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,但我没有。

2 个答案:

答案 0 :(得分:1)

那不是吗?破解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'

答案 1 :(得分:0)

http://code.google.com/p/mockito-python/

>>> from mockito import *
>>> dog = mock()
>>> when(dog).bark().thenReturn("wuff")
>>> dog.bark()
'wuff'

http://technogeek.org/python-module.html - 如何替换,动态加载模块

相关问题