Reputation: 991
Take this example, func_to_test_script.py
from module import ClassA
def func_to_test():
instance_b = ClassA.method_a()
foo = instance_b.method_b()
method_a
returns an instance of class ClassB
.
I want to mock the calls of methods method_a
and method_b
, so I do
@mock.patch("func_to_test_script.ClassA", ClassAMock)
@mock.patch("func_to_test_script.ClassB", ClassBMock)
def test_func_to_test(self):
# test
I can do this with ClassA
(that was imported in func_to_test
's file), but with ClassB
I get the error
AttributeError: <module 'module' from 'func_to_test_script.py'> does not have the attribute 'ClassB'
Upvotes: 0
Views: 1065
Reputation: 10709
First, it will really fail because ClassB
is not defined nor imported in func_to_test_script.py. But even if it is, there is still no need to patch it because it wouldn't take effect anyways. Why? Because the instance of ClassB
will come from the response of ClassA
, which you already mocked.
What you can do is control it from the mock of ClassA
:
@mock.patch("func_to_test_script.ClassA")
def test_func_to_test(self, mock_class_a):
mock_class_a.method_a.return_value.method_b.return_value = "value of foo"
...
Upvotes: 2