【发布时间】:2020-04-07 01:07:24
【问题描述】:
我想使用 [pytest monkeypatch][1] 模拟一个导入的类 到一个单独的模块中。这实际上是否可能,如果可以,如何做到这一点?似乎我还没有看到这种确切情况的示例。假设您有应用程序并在 something.py 中导入了 A 类
from something import A #Class is imported
class B :
def __init__(self) :
self.instance = A() #class instance is created
def f(self, value) :
return self.instance.g(value)
在我的 test.py 中,我想在 B 中模拟 A
from something import B
#this is where I would mock A such that
def mock_A :
def g(self, value) :
return 2*value
#Then I would call B
c = B()
print(c.g(2)) #would be 4
I see how monkeypatch can be used to patch instances of classes, but how is it done for classes that have not yet been instantiated? Is it possible? Thanks!
[1]: https://docs.pytest.org/en/latest/monkeypatch.html
【问题讨论】:
标签: python class pytest monkeypatching