So, I have watched Raymond Hettinger's presentation super considered super and the ability to leverage dependency injection using super and multiple inheritance https://youtu.be/EiOglTERPEo
In one of his examples he is showing us how he'd mock a dependency by introducing a mock implementation of a base class and use this mock in a new childclass implementation in order to provide testability:
class Robot(object):
def left(self):
print("walking left")
def right(self):
print("walking right")
class MyRobot(Robot):
def clean(self):
super().left()
super().right()
Now, in order to test MyRobot independently of the implementation of Robot, one should, according to his presentation, provide a mock implementation of Robot and use this in a new Testable class
class MockRobot(Robot):
def left(self):
print("mock left")
def right(self):
print("mock right")
class MyRobotTestable(MyRobot, MockRobot):
pass
I understand how Method Resolution Order allows us to use the methods of MockRobot in the new testable class.
To be honest, I don't think of this as a good solution, since I am not testing my actual code on top of that I am introducing a new "class", yet only for the reason to make another class testable.
Coming from other OOP languages: Is there any reason, not to inject the dependency via the constructor?
i.e.:
class MyRobot(object):
def __init__(robot):
self.robot = robot
def clean(self):
self.robot.left()
self.robot.right()
I don't need any additional class to provide testability (apart from the mock) and I can inject whatever implementation I want.
I consider this proper OOP following the Dependency Inversion rule.
Aucun commentaire:
Enregistrer un commentaire