Skip to main content
 首页 » 编程设计

在 __init__ 中定义和设置的 Python 模拟属性

2025年05月04日11mfryf

我正在尝试为应用程序编写一些单元测试,并且我使用的是 python mock。我熟悉其他模拟库,直到现在才遇到太多麻烦。我正在尝试模拟对父类的 init block 中的属性集的链式调用。这是我需要的示例:

class ApplicationUnderTest: 
 
    def __init__(self): 
      self.attributeBeginningChain = SomeClass(False) 
 
    def methodWithChain(self): 
      object = self.attributeBeginningChain.methodOfSomeClass() 

我需要链式调用来抛出错误。我尝试通过以下方式解决此问题:

@patch.object(SomeClass(False), 'methodOfSomeClass', side_effect=ErrorClass) 
def test_chained_call(self, mock_someclass): 
    A = ApplicationUnderTest.methodWithChain() 
    self.assertTrue(mock_someclass.called) 

最后一个断言失败了,所以我很确定这不是执行此操作的方法。我也试过:

@patch('ApplicationUnderTest.attributeBeginningChain') 
def test_chained_call(self, mock_someclass): 
    mock_someclass.methodOfSomeClass.side_effect = ErrorClass 
    A = ApplicationUnderTest.methodWithChain() 
    self.assertTrue(mock_someclass.called) 

抛出错误:

AttributeError: package.ApplicationUnderTest does not have the attribute 'attributeBeginningChain' 

我无法更改被测代码,所以我的问题是如何模拟对在 _init__ 函数?我读到这是不可能的,但肯定有解决办法吗?我是否可以通过 autospec 以某种方式指示模拟夹具对调用本身而不是属性对象使用react?

请您参考如下方法:

attributeBeginningChain 实例属性由 __init__ 设置,因此您通过 patch 设置的修补静态值调用 ApplicationUnderTest 调用将被 __init__ 调用覆盖。

您应该改为修补 ApplicationUnderTest 实例:

def test_chained_call(self): 
    A = ApplicationUnderTest() 
    with patch.object(A, 'attributeBeginningChain') as mock_someclass: 
        mock_someclass.methodOfSomeClass.side_effect = ErrorClass 
        with self.assertRaise(ErrorClass): 
            A.methodWithChain() 

另一种可能性是直接打补丁 SomeClass.methodOfSomeClass

@patch('package.SomeClass.methodOfSomeClass', side_effect=ErrorClass) 
def test_chained_call(self, mock_methodOfSomeClass): 
    with self.assertRaise(ErrorClass): 
        ApplicationUnderTest().methodWithChain() 

我不确定您的对象在哪里以及您应该如何修补它们:看看 where to patch了解您应该如何使用 patch 调用。