在_init中定义和设置Python模拟属性__
我正在尝试为一个应用程序编写一些单元测试,我正在使用PythonMock。我熟悉其他mocking库,到目前为止还没有遇到太多麻烦。我试图模拟父类的init块中的属性集上的链式调用。以下是我需要的一个示例:在_init中定义和设置Python模拟属性__,python,unit-testing,python-mock,Python,Unit Testing,Python Mock,我正在尝试为一个应用程序编写一些单元测试,我正在使用PythonMock。我熟悉其他mocking库,到目前为止还没有遇到太多麻烦。我试图模拟父类的init块中的属性集上的链式调用。以下是我需要的一个示例: class ApplicationUnderTest: def __init__(self): self.attributeBeginningChain = SomeClass(False) def methodWithChain(self): o
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'
我不能对测试中的代码进行修改,所以我的问题是如何模拟在
_初始化函数?我读到这是不可能的,但肯定有一个解决办法?我是否可以通过autospec指示模拟装置对调用本身而不是属性对象作出反应?
attributeBeginningChain
实例属性由\uuuuu init\uuuuu
设置,因此由patch
调用ApplicationUnderTest
调用设置的补丁静态值将被\uuuu初始化\uuuu
调用
您应该改为修补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()
我不确定您的对象在哪里,因此您应该如何修补它们:请查看以了解您应该如何使用
patch
呼叫。谢谢您的回复!我还没有尝试过这个(转到其他方面),但我会检查一下,等我回来再回答。