python mock default init argument of class
Question: I want to mock the default argument in a class constructor:

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

I want to mock `DefaultConnection` in my unittests, but it doesn't work when
passed in as a default value.


Answer: You can use patch to
[patch](https://docs.python.org/3/library/unittest.mock.html#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()
      ....
    

