pythonmox

Use mox to mock a method called by__init__


I'd like to stub out a single method in a class that is called by the init method.

class MyClass(object):
  def __init__(self): 
    # Some initializer code here
    ...
    self.method_with_side_effects()

  def method_with_side_effects(self):
    ... # Load files, etc.

According to the Mox documentation, you can mock a method by instantiating the object and then using the StubOutWithMock method. But in this case, I can't do that:

import mox
m = mox.Mox()
myobj = MyClass()
m.StubOutWithMock(myobj, "method_with_side_effects") # Too late!

Is there any other way to stub out that method?


Solution

  • Could you subclass MyClass directly and override method_with_side_effects?