問題描述
是否可以模擬在我嘗試測試的另一個函數中調用的函數的返回值?我希望模擬方法(將在我正在測試的許多方法中調用)在每次調用時返回我指定的變量.例如:
Is it possible to mock a return value of a function called within another function I am trying to test? I would like the mocked method (which will be called in many methods I'm testing) to returned my specified variables each time it is called. For example:
class Foo:
def method_1():
results = uses_some_other_method()
def method_n():
results = uses_some_other_method()
在單元測試中,我想用mock來改變uses_some_other_method()
的返回值,這樣在Foo
中任何時候調用它都會返回我在 @patch.object(...)
In the unit test, I would like to use mock to change the return value of uses_some_other_method()
so that any time it is called in Foo
, it will return what I defined in @patch.object(...)
推薦答案
有兩種方法可以做到這一點;帶補丁和帶補丁.object
There are two ways you can do this; with patch and with patch.object
Patch 假定您不是直接導入對象,而是您正在測試的對象正在使用它,如下所示
Patch assumes that you are not directly importing the object but that it is being used by the object you are testing as in the following
#foo.py
def some_fn():
return 'some_fn'
class Foo(object):
def method_1(self):
return some_fn()
#bar.py
import foo
class Bar(object):
def method_2(self):
tmp = foo.Foo()
return tmp.method_1()
#test_case_1.py
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,如下:
If you are directly importing the module to be tested, you can use patch.object as follows:
#test_case_2.py
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 都將在測試功能完成后取消模擬".
In both cases some_fn will be 'un-mocked' after the test function is complete.
為了模擬多個函數,只需在函數中添加更多裝飾器并添加參數以接收額外的參數
In order to mock multiple functions, just add more decorators to the function and add arguments to take in the extra parameters
@patch.object(foo, 'some_fn')
@patch.object(foo, 'other_fn')
def test_foo(test_other_fn, test_some_fn):
...
請注意,裝飾器越接近函數定義,它在參數列表中的位置就越早.
Note that the closer the decorator is to the function definition, the earlier it is in the parameter list.
這篇關于使用 python 的模擬 patch.object 更改在另一個方法中調用的方法的返回值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!