Reputation: 362
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.
@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'
Upvotes: 1
Views: 24
Reputation: 531480
The thing you need to mock is the entry for B
in A.__init__.__globals__
.
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
Upvotes: 2