【问题标题】:What is a clean way of mocking multiple methods on a class in python?在python中模拟一个类的多个方法的干净方法是什么?
【发布时间】:2017-12-18 03:04:15
【问题描述】:

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

有没有更简洁/推荐的方法?如果能够移除多个嵌套调用,那就太好了!

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

【问题讨论】:

  • A 中是否还有其他方法可以在测试中运行,并且不会被模拟?
  • 谢谢@solarissmoke 我已经更新了问题以补充可能有也可能没有非模拟方法

标签: python django unit-testing mocking


【解决方案1】:

您不需要嵌套上下文管理器 - 您可以一次性修补所有方法:

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

您也可以使用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

【讨论】:

    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-15
    • 2021-10-29
    相关资源
    最近更新 更多