Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Mocking private methods in python
""" This is a simple gist to show how to mock
private methods. I've got lots of questions
regarding this topic. Most people seems confused.
Hope it helps.
"""
import unittest
import mock
class Car:
def __private(self):
return 1
def no_private(self):
return self.__private()
class CarTest(unittest.TestCase):
def test_exception_raises(self):
c = Car()
with self.assertRaises(AttributeError):
c.__private()
def test_car_works(self):
c = Car()
self.assertEqual(c.no_private(), 1)
def test_mock_private(self):
c = Car()
with mock.patch.object(c, '_Car__private', return_value=3) as method:
c.no_private()
method.assert_called_once_with()
if __name__ == "__main__":
unittest.main()
@rahulrajaram

This comment has been minimized.

Copy link

commented Aug 25, 2017

Awesome, thanks.

In particular, your test_mock_private example helped me.

@namaggarwal

This comment has been minimized.

Copy link

commented Nov 22, 2017

Thanks. This is what I was looking for :)

@jmrf

This comment has been minimized.

Copy link

commented Nov 23, 2017

Thanks, this is perfect!

@BrianBohe

This comment has been minimized.

Copy link

commented Jan 30, 2018

Thanks a lot!

@BISASAM

This comment has been minimized.

Copy link

commented Jun 5, 2018

+1

@MSabherwal

This comment has been minimized.

Copy link

commented Jun 12, 2018

ty!

@dnyaneshwarmore

This comment has been minimized.

Copy link

commented Oct 5, 2018

wow very simple and clear

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.