python mock default init argument of class

2019-07-13 05:23发布

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条回答
一纸荒年 Trace。
2楼-- · 2019-07-13 05:56

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()
  ....
查看更多
登录 后发表回答