问题
Is there a way to mock just the default parameters of a class constructor? For example, if I have this class:
class A (object):
def __init__(self, details='example'):
self.details = details
Is there a way to a mock just the default value of the details argument, eg to details='test'?
回答1:
Surely this is simplest:
class TestA (A):
def __init__(self, details='test'):
super(TestA, self).__init__(details)
If you're not able to use TestA without changing code elsewhere, then you could try something a bit more direct:
>>> A().details
'example'
>>> A.__old_init = A.__init__
>>> A.__init__ = lambda self, details='test': self.__old_init(details)
>>> A().details
'test'
If your willing to go that far, though, why not do it the tidy way?
class A (object):
_DEFAULT_DETAILS = 'details'
def __init__(self, details=None):
if details is None:
self.details = self._DEFAULT_DETAILS
else:
self.details = details
Now you can override the default value without resorting to any trickery:
A._DEFAULT_DETAILS = 'test'
回答2:
Would a new mock class do?
class Amock(A):
def __init__(self, details='newdefault'):
super(Amock, self).__init__(details=details)
来源:https://stackoverflow.com/questions/36704191/mocking-class-constructor-default-parameters-in-python