Mock super().__init__

Viewed 50

I have a parent class that, within its __init__ calls some internal class methods:

class Parent:
  def __init__(self):
    ...
    my_method()

  def my_method(self, a...):
     pass 

Afterwards, I create a child class that relies on that Parent class. After creating instance objects of the Child class, they explicitly invoque the parent's __init__ method

class Child(Parent):
  def __init__(self, a):
    super().__init__(a)

I would like to mock the parent class such that I can test its child without fully relying on the parent's initialization function, which calls my_method. This my_method is problematic and causes the test of the Child to fail due to its parent necessarily calling that method.

Answers with pytest would be appreciated

1 Answers

A simple way to prevent the parent class from calling my_method during initialization, would be to pass an extra argument to the __init__ function of the parent that specifies whether the method should be called.

class Parent:
  def __init__(self, call_method=True):
    ...

    if call_method:
        my_method()

  def my_method(self, a...):
     pass 

And then in the child class:

class Child(Parent):
  def __init__(self, a, call_method=True):
    super().__init__(call_method)

When instantiating Child classes during testing, simply set call_method to false.

child = Child(call_method=False)
Related