在python中对类的多个方法进行模拟的简洁方法是什么?

时间:2017-12-18 03:04:15

标签: python django unit-testing mocking

在编写测试时,我常常面临模拟几个类方法的需要。目前我通过嵌套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

是否有更简洁/推荐的方法?能够删除多个嵌套调用会很好!

在此过程中,类中可能有或没有其他未被模拟的方法。

1 个答案:

答案 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