I have a method that I would like to unit test - run. During initialization of my class, I pass an object of another class to it. The said object fetches data with it's method.
class MyClass:
def __init__(self, data_obj):
self.data_obj = data_obj
self.id = 100
def run():
data = self.data_obj.fetchData(self.id)
Now when I am writing my unit test, I don't want to initialize the data class again because during it's initialization, it makes a lot of expensive API calls which I don't want to repeat.
How can I mock the data_obj and the data_obj's method fetchData?
Now what I want to do is to test the run method by providing a fake id and what the fake id is supposed to return and test the whole flow of the run method. How do I mock out the data's class object which is passed to my class and say what it is supposed to return?
class TestRunMethod(unittest.TestCase):
def test_run(self):
mc = MyClass(mock_data_obj)
self.id = 200 # some fake id
# Make self.data_obj.fetchData(id=200) return 'xyz'
output = mc.run()
assertEqual(output, 'xyz')
I was reading the tutorials of mocking. I think what I need to do is to patch the data_obj's method and specify a return value
@patch('mymodule.test.Data')
class TestRunMethod(unittest.TestCase):
def test_run(self, mock_data_obj):
mc = MyClass(mock_data_obj)
self.id = 200 # some fake id
mock_data_obj.fetchData(self.id).return_value = 'xyz'
output = mc.run()
assertEqual(output, 'xyz')
Is this correct? If not how should I correct this?