使用@patch 装饰器模拟 class 属性
Mock class attribute with @patch decorator
如何使用 @patch
装饰器模拟正在测试的 class 的对象 属性?
给出以下测试:
def test_hangup(self):
stub_call = Mock()
cut = TelefonyInterface()
cut.call = stub_call
cut.hangup()
self.assertEqual(1, stub_call.hangup.call_count)
self.assertEqual(None, cut.call)
我想在这里使用 mock.patch
装饰器以使其更易于阅读。像这样:
@patch.object(TelefonyInterface, 'call')
def test_hangup(self, call):
cut = TelefonyInterface()
cut.hangup()
self.assertEqual(1, call.hangup.call_count)
self.assertEqual(None, cut.call)
但我得到以下 AttributeError:
AttributeError: <class '(...).TelefonyInterface'> does not have the attribute 'call'
我的 TelefonyInterface 看起来像这样:
class TelefonyInterface:
def __init__(self):
self.call = None
def dial(self, number):
self.call = ...
def hangup(self):
if self.call:
self.call.hangup()
...
执行此操作的正确方法是什么?
这里的问题是您正在修补没有属性 call
的 TelefonyInterface
class。该属性是在初始化时在实例上定义的。要完成您想要修补实例而不是 class:
def test_hangup(self):
cut = TelefonyInterface()
with patch.object(cut, 'call') as call:
cut.hangup()
self.assertEqual(1, call.hangup.call_count)
self.assertEqual(None, cut.call)
如何使用 @patch
装饰器模拟正在测试的 class 的对象 属性?
给出以下测试:
def test_hangup(self):
stub_call = Mock()
cut = TelefonyInterface()
cut.call = stub_call
cut.hangup()
self.assertEqual(1, stub_call.hangup.call_count)
self.assertEqual(None, cut.call)
我想在这里使用 mock.patch
装饰器以使其更易于阅读。像这样:
@patch.object(TelefonyInterface, 'call')
def test_hangup(self, call):
cut = TelefonyInterface()
cut.hangup()
self.assertEqual(1, call.hangup.call_count)
self.assertEqual(None, cut.call)
但我得到以下 AttributeError:
AttributeError: <class '(...).TelefonyInterface'> does not have the attribute 'call'
我的 TelefonyInterface 看起来像这样:
class TelefonyInterface:
def __init__(self):
self.call = None
def dial(self, number):
self.call = ...
def hangup(self):
if self.call:
self.call.hangup()
...
执行此操作的正确方法是什么?
这里的问题是您正在修补没有属性 call
的 TelefonyInterface
class。该属性是在初始化时在实例上定义的。要完成您想要修补实例而不是 class:
def test_hangup(self):
cut = TelefonyInterface()
with patch.object(cut, 'call') as call:
cut.hangup()
self.assertEqual(1, call.hangup.call_count)
self.assertEqual(None, cut.call)