Skip to content Skip to sidebar Skip to footer

Python Mock Default Init Argument Of Class

I want to mock the default argument in a class constructor: class A (object): def __init__(self, connection=DefaultConnection()): self.connection = connection I want t

Solution 1:

You can use patch to patch the module, and then you can set the return value as a Mock.

# --- a.py (in package path x.y) --
from c import DefaultConnection

class A (object):
    def __init__(self, connection=DefaultConnection()):
        self.connection = connection

#---- a_test.py ----
from mock import patch
from a import A

@patch('x.y.a.DefaultConnection')
def test(def_conn_mock):
  conn_mock = Mock()
  def_conn_mock.return_value = conn_mock

  a_obj = A()
  ....

Post a Comment for "Python Mock Default Init Argument Of Class"