[英]Mock calls to class constructor with different class
I have the following classes: 我有以下课程:
class A(object):
def __init__(self):
self.inner_class = B()
def foo():
self.inner_class.bar()
class B(object):
def bar():
return 'No'
class C(object):
def bar():
return 'Yes'
I want to mock such that instead of calling the constructor of B it will get a C object. 我想模拟这样,而不是调用B的构造函数,而是得到一个C对象。
@patch(...something....)
def test_get_yes(self):
A().foo() # Expected output is 'Yes'
How can I do it? 我该怎么做?
I know I can write the following test but I prefer not to: 我知道我可以编写以下测试,但我不愿意:
def test_get_yes(self):
a = A()
a.inner_class = C()
a.foo() # Expected output is 'Yes'
The thing you need to mock is the entry for B
in A.__init__.__globals__
. 您需要模拟的是A.__init__.__globals__
B
的条目。
Assuming a slightly different set of class definitions than appear in your question: 假设一组类定义与您的问题中出现的稍有不同:
class A(object):
def __init__(self):
self.inner_class = B()
def foo(self):
return self.inner_class.bar()
class B(object):
def bar(self):
return 'No'
class C(object):
def bar(self):
return 'Yes'
Then the following should work: 然后,以下应该工作:
@patch.dict(A.__init__.__globals__, {'B': C})
def test_get_yes():
print(A().foo())
test_get_yes() # Outputs yes, not no
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.