使用 mox 模拟一个名为 by__init__ 的方法

发布于 2024-11-16 10:42:36 字数 494 浏览 3 评论 0原文

我想在由 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

落叶缤纷 2024-11-23 10:42:36

您可以直接子类化MyClass并覆盖method_with_side_effects吗?

Could you subclass MyClass directly and override method_with_side_effects?

命硬 2024-11-23 10:42:36

如果你只想存根该方法,你可以使用stubout模块:

import stubout

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

如果你真的想模拟该方法,那就更复杂了。您可以直接使用 __new__() 创建一个实例对象,以避免 __init__() 的副作用,并用它来记录预期的行为:

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 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文