Python单元测试类属性

时间:2017-08-14 18:10:41

标签: python python-unittest python-unittest.mock

我试图找出是否有办法(单元测试)验证实际调用属性和setter来设置name属性。

class DummyName:
    def __init__(self):
        self.name = ''

    @property
    def name(self):
        return self.name

    @name.setter
    def name(self, name):
        if not isinstance(name, basestring):
            raise Exception('Name must be a string.')
        self.name = name

尝试做这样的事情......

@mock.patch.object(DummyName, 'name', new_callable=PropertyMock)
def testNameProperty(self, mock_name):
    MockName = Mock()
    mock_name.return_value = MockName
    dummyName = DummyName()
    dummyName.name = 'test_name'
    # assert setter is called to set the name
    # assert name is called to get the name
    # assert name is 'test_name'

似乎从不访问name()和setter。任何人都有更好的主意?谢谢!

2 个答案:

答案 0 :(得分:4)

通过使用这样的模拟,你已经覆盖了你试图测试的代码。模拟用于被测代码外部的调用。

对此代码的适当测试是声明如果传递的内容不是字符串,则会引发异常。

def testNameProperty(self):
    dummyName = DummyName()
    with self.assertRaises(Exception):
        dummyName.name = 12345

答案 1 :(得分:2)

您的课程需要继承mapfile -t arr < <(printf '%s' "$s" | awk -v RS="-mode[[:space:]]*" 'NR>1') # examine array content declare -p arr declare -a arr=([0]="FOO" [1]="BAR" [2]="BAZ" [3]="BAG" [4]="DAT" [5]="RAR")

object

您还需要为类中的class DummyName(object): def __init__(self): self._name = '' @property def name(self): return self._name @name.setter def name(self, name): if not isinstance(name, basestring): raise Exception('Name must be a string.') self._name = name 使用不同的变量,否则您将达到最大递归。