使用@patch装饰器测试类的模拟属性

时间:2018-06-25 12:56:52

标签: python unit-testing mocking decorator patch

如何使用@patch装饰器模拟正在测试的类的对象属性?

给出以下测试:

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()

使用@patch装饰器执行此操作的正确方法是什么?

0 个答案:

没有答案
相关问题