假设我有这种情况:
module2.py
class Bar:
def bar():
a = 5
# do stuff
Messages.show("Done")
module1.py
import module2
class Foo:
def __init__(self):
self.bar = module2.Bar()
def foo(self):
self.bar.bar()
我想测试方法 Foo.foo(),但我想忽略 Messages.show("Done),即我想在模拟对象上调用 Messages.show 函数。如果 foo 正在调用Messages.show 直接,我可以在 foo 上使用 monkeypatch 来模拟 Messages 类。但是现在,我从另一个模块调用一个类,我不知道如何指定 Messages.show 调用不应该完成(原因因为他们访问 Gui 并且在测试环境中不起作用。假设我无法修改 module2.py。
最佳答案
只需覆盖 module2
认为 Messages
是什么:
import module2
module2.Messages = ...
关于python - 猴子修补从子方法调用的函数中的类 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27730823/