8

我在一个模块中有以下方法,它调用从另一个模块导入的另一个方法:

def imported_function():
    do_unnecessary_things_for_unittest()

实际需要测试的方法,导入并使用上述函数:

from somewhere import imported_function

def function_to_be_tested():
    imported_function()
    do_something_more()
    return 42

import_function中的内部调用和相关计算并不重要,它们也不是我想要测试的,所以我只想在测试实际函数function_to_be_tested时跳过它们。

因此,我尝试对测试方法中某处命名的模块进行猴子补丁,但没有运气。

def test_function_to_be_tested(self):
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True

问题是,如何在测试时对模块的方法进行修补,以便在测试阶段不会调用它?

4

2 回答 2

15

I think better to use Mock Library

So you can do something like:

from somewhere import imported_function

@patch(imported_function)
def test_function_to_be_tested(self, imported_function):
    imported_function.return_value = True
    #Your test

I think for unit tests it's better than monkey patch.

于 2012-08-31T08:34:23.283 回答
8

假设您有以下文件:

某处.py

def imported_function():
    return False

测试文件

from somewhere import imported_function

def function_to_be_tested():
    return imported_function()

A call to testme.function_to_be_tested() would return False.


Now, the trick is to import somewhere before testme:

import somewhere
somewhere.__dict__['imported_function'] = lambda : True

import testme
def test_function_to_be_tested():
    print testme.function_to_be_tested()

test_function_to_be_tested()

Output:

True


Or, reload the testme module

import testme

def test_function_to_be_tested():
    print testme.function_to_be_tested()
    import somewhere
    somewhere.__dict__['imported_function'] = lambda : True
    print testme.function_to_be_tested()
    reload(testme)
    print testme.function_to_be_tested()

test_function_to_be_tested()

Output:

False
False
True

于 2012-08-31T08:01:05.847 回答