3

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.

Atul Bhatia
  • 1,633
  • 5
  • 25
  • 50
  • how to you both pass it as a default value plz? I thought that the default is there if you DON'T pass a value... also executing class initialization code during definition of another class is not very wise (`DefaultConnection()` is executed already during import of the module, not during initialization of `a = A()` if I understand it correctly) – Aprillion Jan 15 '16 at 20:49
  • Possible duplicate of [Mocking class constructor default parameters in Python](http://stackoverflow.com/questions/36704191/mocking-class-constructor-default-parameters-in-python) – Reut Sharabani Apr 18 '16 at 21:07

1 Answers1

2

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()
  ....
Uri Shalit
  • 2,198
  • 2
  • 19
  • 29