Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:模拟一个';模块I'正在使用s;m测试_Python_Unit Testing_Mocking - Fatal编程技术网

Python:模拟一个';模块I'正在使用s;m测试

Python:模拟一个';模块I'正在使用s;m测试,python,unit-testing,mocking,Python,Unit Testing,Mocking,我想模拟某个模块,以便测试使用该模块的代码 也就是说,我有一个我想测试的模块my_modulemy\u module导入外部模块real\u thing并调用real\u thing.compute\u something(): 我需要模拟真实的东西,以便在测试中它的行为类似于虚假的东西,我创建了一个模块: #fake_thing def compute_something(): return fake_value 测试调用my\u module.my\u function(),该函数

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

也就是说,我有一个我想测试的模块
my_module
my\u module
导入外部模块
real\u thing
并调用
real\u thing.compute\u something()

我需要模拟
真实的东西
,以便在测试中它的行为类似于
虚假的东西
,我创建了一个模块:

#fake_thing
def compute_something():
    return fake_value
测试调用
my\u module.my\u function()
,该函数调用
real\u thing.compute\u something()

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

我一直在想如何使用它,但我没有。


-如何更换、动态加载模块?破解系统模块

#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()

输出:“伪值”

将伪值导入为真实值”
放在测试文件的顶部如何?我总是发现模拟模块的最简单方法是直接指向它,然后大喊:“哈哈,你是一个模块!”@David:这解决不了问题。测试执行my_模块。my_函数()和my_模块不知道它是从测试中调用的
my_模块
imports
real_thing
,因此,
real_thing.compute_thing()
将被执行,无论测试模块中实际导入了什么模块。您的答案对我没有帮助,因为在我的问题中还有一个间接层次:让我们说
dog.bark()
调用
dog.Innovate()()
我想模拟
dog.吸气()
这样在测试中,当调用
dog.bark()
时,会被称为我的假
dog.吸气()
而不是真正的
dog.吸气()
。这怎么办呢?你是对的,我在python中添加了动态模块加载的链接。其背后的想法是,一旦你按下模块名,python就会重用同一个模块而不重新加载。我已经测试了它,但它不起作用。
my_Module.my_function()
仍然不会返回假值;它调用
real\u thing.calculate\u something()
并因此返回真实值。请确保在执行sys.modules技巧后导入我的\u模块,否则它将不起作用。我已明确说明了我的测试用例,以便您可以复制它
#test_my_module
import my_module
def test_my_function():
    assert_something(my_module.my_function())
>>> from mockito import *
>>> dog = mock()
>>> when(dog).bark().thenReturn("wuff")
>>> dog.bark()
'wuff'
#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()