在编写测试时,我常常面临模拟几个类方法的需要。目前我通过嵌套with
语句包含mock
引用,例如
from ... import A
def test_sample(self)
instance = A()
with mock(A, 'function_1', return_value=1):
with mock(A, 'function_2', return_value=2):
with mock(A, 'function_3', return_value=3):
assert A.function_4, 10
是否有更简洁/推荐的方法?能够删除多个嵌套调用会很好!
在此过程中,类中可能有或没有其他未被模拟的方法。
答案 0 :(得分:1)
You don't need to have nested context managers - you can patch all the methods in one go:
def test_sample(self)
instance = A()
with (mock(A, 'function_1', return_value=1),
mock(A, 'function_2', return_value=2),
mock(A, 'function_3', return_value=3)):
assert A.function_4, 10
Alternatively you can use patch.multiple
:
from unittest import patch
def test_sample(self)
instance = A()
with patch.multiple(A, function_1=2, function_2=2, function_3=3) as patched_values:
assert A.function_4, 10