Search code examples
pythonpython-unittestpython-unittest.mock

Python unit testing Class properties


I am trying to figure out if there's a way to (unit test) verify that the property and the setter is actually called to set the name attribute.

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

Trying to do something like this...

@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'

Seems like name() and setter are never accessed. the Anyone has a better idea? Thanks!


Solution

  • By using mocks like that you've overwritten the code you're trying to test. Mocks are for calls that are external to the code under test.

    An appropriate test for this code is to assert that the exception is raised if you pass something that isn't a string.

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