使用 mox 模拟一个名为 by__init__ 的方法
我想在由 init 方法调用的类中删除一个方法。
class MyClass(object):
def __init__(self):
# Some initializer code here
...
self.method_with_side_effects()
def method_with_side_effects(self):
... # Load files, etc.
根据 Mox 文档,您可以通过实例化对象然后使用 StubOutWithMock 方法来模拟方法。但在这种情况下,我不能这样做:
import mox
m = mox.Mox()
myobj = MyClass()
m.StubOutWithMock(myobj, "method_with_side_effects") # Too late!
还有其他方法可以消除该方法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以直接子类化
MyClass
并覆盖method_with_side_effects
吗?Could you subclass
MyClass
directly and overridemethod_with_side_effects
?如果你只想存根该方法,你可以使用stubout模块:
如果你真的想模拟该方法,那就更复杂了。您可以直接使用 __new__() 创建一个实例对象,以避免 __init__() 的副作用,并用它来记录预期的行为:
如果您实际上不这样做需要行为验证,使用存根而不是模拟更不脆弱。
If you only want to stub out the method, you can use the stubout module:
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:If you don't actually need behavior verification, using stubs instead of mocks is much less fragile.