您可以通过两种方式执行此操作;与patch和patch.object
修补程序假定您不是直接导入对象,而是要测试的对象正在使用它,如下所示
def some_fn():
return 'some_fn'
class Foo(object):
def method_1(self):
return some_fn()
import foo
class Bar(object):
def method_2(self):
tmp = foo.Foo()
return tmp.method_1()
import bar
from mock import patch
@patch('foo.some_fn')
def test_bar(mock_some_fn):
mock_some_fn.return_value = 'test-val-1'
tmp = bar.Bar()
assert tmp.method_2() == 'test-val-1'
mock_some_fn.return_value = 'test-val-2'
assert tmp.method_2() == 'test-val-2'
如果直接导入要测试的模块,则可以按如下方式使用patch.object:
import foo
from mock import patch
@patch.object(foo, 'some_fn')
def test_foo(test_some_fn):
test_some_fn.return_value = 'test-val-1'
tmp = foo.Foo()
assert tmp.method_1() == 'test-val-1'
test_some_fn.return_value = 'test-val-2'
assert tmp.method_1() == 'test-val-2'
在这两种情况下,测试功能完成后,some_fn都将被“取消模拟”。
编辑:为了模拟多个功能,只需向功能添加更多装饰器,并添加参数以接受额外的参数
@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
...
请注意,装饰器离函数定义越近,它在参数列表中的位置就越早。