Skip to content

Instantly share code, notes, and snippets.

@igniteflow
Created October 3, 2016 11:03
Show Gist options
  • Star 20 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save igniteflow/1be88c18185ffe42a66a46e48118f486 to your computer and use it in GitHub Desktop.
Save igniteflow/1be88c18185ffe42a66a46e48118f486 to your computer and use it in GitHub Desktop.
How to mock an object property in Python
import mock
with mock.patch('path.to.ObjectClass.my_property', new_callable=mock.PropertyMock) as mock_my_property:
mock_my_property.return_value = 'my value'
@andrew-lub
Copy link

thanks!

@jorgeas80
Copy link

Good one. Thanks!

@audy
Copy link

audy commented Dec 16, 2021

Thank you!

This also works:

import mock

with mock.patch("...", new_callable=mock.PropertyMock, return_value="my value"):
    ...

@zhixuan-loh
Copy link

Can someone please demonstrate how to do it in other forms? I.e. without a context manager

@abhai-srijan
Copy link

HI I am using the same thing . The property is getting mocked properly with the proper value that i have set , but when i call the method to test which uses this property , the actual property is getting called instead of this mock that i have created .

@abhai-srijan
Copy link

Can someone please demonstrate how to do it in other forms? I.e. without a context manager

there is one decorator method:

@patch("...", new_callable=mock.PropertyMock,return_value="some_value")
def test_fun(self, mock):
    pass

@lhoncorty
Copy link

Cool. Thanks. It saved me hours.

@lhoncorty
Copy link

lhoncorty commented Jun 12, 2023

Can someone please demonstrate how to do it in other forms? I.e. without a context manager

there is one decorator method:

@patch("...", new_callable=mock.PropertyMock,return_value="some_value")
def test_fun(self, mock):
    pass
@patch('path.to.ObjectClass.my_property', new_callable=mock.PropertyMock)
def test_fun(self, mock):
    mock.return_value="some_value"
    pass

@Alfo5123
Copy link

Alfo5123 commented Jul 9, 2023

Thanks!

@khalilgreenidge
Copy link

@lhoncorty Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment