I am trying to test whether a function defined outside of a class is called by a class method.
def function_a(input):
return input
class MyClass:
def __init__(self, user_function=function_a):
self.user_function = user_function
def function_b(input):
return self.user_function(input)
I am trying to test the function call like this:
from unittest import TestCase
from unittest.mock import Mock
class TestMyClass(TestCase):
def test_function_call(self):
my_class = MyClass(user_function=function_a)
mock = Mock()
my_class.function_b(input)
mock.function_a.assert_called()
This gives me
AssertionError: Expected 'function_a' to have been called.
I am using Python 3.6. Looking at the output I can see that function_a was called. What am I doing wrong?
CodePudding user response:
This here did the trick:
from unittest import TestCase
from unittest.mock import MagicMock
class TestMyClass(TestCase):
def test_function_call(self):
my_class = MyClass(user_function=MagicMock())
my_class.function_b(input)
my_class.user_function.assert_called()