【问题标题】:Mocking a Constructor Helper Method in Python在 Python 中模拟构造函数辅助方法
【发布时间】:2013-09-17 19:22:45
【问题描述】:

我以下列方式定义了我的构造函数。

def __init__(self):
    //set some properties
    ...
    self.helperMethod()

def helperMethod(self):
    //Do some operation

我想对辅助方法进行单元测试,但是为了创建对象来进行单元测试,我需要运行__init__ 方法。但是,这样做会调用辅助方法,这是不可取的,因为这是我需要测试的方法。

我尝试模拟出__init__ 方法,但收到__init__ should return None and not MagicMock 的错误。

我也尝试通过以下方式模拟出辅助方法,但我找不到手动恢复模拟方法的方法。 MagicMock.reset_mock() 不这样做。

SomeClass.helperMethod = MagicMock()
x = SomeClass()
[Need someway to undo the mock of helperMethod here]

对帮助方法进行单元测试的最佳方法是什么?

【问题讨论】:

    标签: python unit-testing mocking


    【解决方案1】:

    您是否尝试过捕获helperMethod 的原始值?

    original_helperMethod = SomeClass.helperMethod
    SomeClass.helperMethod = MagicMock()
    x = SomeClass()
    SomeClass.helperMethod = original_helperMethod
    

    您还可以使用 mock 库中的 patch 装饰器

    from mock import patch
    
    class SomeClass():
    
        def __init__(self):
            self.helperMethod()
    
        def helperMethod(self):
            assert False, "Should not be called!"
    
    x = SomeClass() # Will assert 
    with patch('__main__.SomeClass.helperMethod') as mockHelpMethod:
        x = SomeClass() # Does not assert
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-28
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      相关资源
      最近更新 更多