开发者

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 开发者_Python百科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?


Could you subclass MyClass directly and override method_with_side_effects?


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜