Skip to content

Mock Class Property in PyTest

It's easy to use Mock for a python method, staticmethod, classmethod, but for propery, it's not just to use Mock. Here are the example to mock a property of a class in python UT.

  • A simple class

    Python
    class Dog:
        @property
        def name(self):
            return "dog"
    
  • Test

    Python
    from unittest.mock import Mock, PropertyMock
    
    from learn.animal.dog import Dog
    
    
    def test_dog():
        dog = Dog()
    
        type(dog).name = PropertyMock(side_effect=["dog1", "dog2"])
    
        assert dog.name == "dog1"
        assert dog.name == "dog1"
    

We can see in the example, that we set the mock property to a PropertyMock by type(object).<property> = PropertyMock(). In the PropertyMock, we can use return_value or side_effect like what we use mocks for a method.