2

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?

Lorin Hochstein
  • 57,372
  • 31
  • 105
  • 141

2 Answers2

3

Could you subclass MyClass directly and override method_with_side_effects?

Daenyth
  • 35,856
  • 13
  • 85
  • 124
1

If you only want to stub out the method, you can use the stubout module:

import stubout

s = stubout.StubOutForTesting()
s.Set(MyClass, 'method_with_side_effects', lambda self: None)

If you actually want to mock the method, it's more complicated. You can create an instance object directly with __new__() to avoid the side effects from __init__(), and use it to record the expected behavior:

import mox

m = mox.Mox()
m.StubOutWithMock(MyClass, 'method_with_side_effects')

instance = MyClass.__new__(MyClass)
instance.method_with_side_effects().AndReturn(None)

m.ReplayAll()
MyClass()
m.VerifyAll()

If you don't actually need behavior verification, using stubs instead of mocks is much less fragile.

mks
  • 11
  • 1