python mock default init argument of class

微笑、不失礼 提交于 2019-12-11 02:38:52

问题


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


来源:https://stackoverflow.com/questions/32000970/python-mock-default-init-argument-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!