python mock default init argument of class

2019-07-13 05:50发布

问题:

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.

回答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()
  ....