1

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?

Piyush
  • 606
  • 4
  • 16
  • 38
  • In unittest, you can define a function `setUp()` that is called *before* the start of each test. So you can initialize your class inside of that function. By expensive API call, do you mean computationally expensive or monetarily expensive like some third party API calls that will charge you each time you do it? I was assuming computationally expensive. – Mia Jul 05 '17 at 02:22
  • @pkqxdd: I meant computationally expensive i.e. making tons of RPC calls to servers which I don't need.I am aware of setUp(). Thing is I don't want to initialize the Data class. I am looking for a way to mock it out. – Piyush Jul 05 '17 at 02:26
  • It's been a while but you may find this question helpful. Sadly I personally don't know how to do that. https://stackoverflow.com/questions/5626193/what-is-a-monkey-patch – Mia Jul 11 '17 at 10:37

0 Answers0