-1

I am implementing the following class:

class TestInitializeConnection(TestMyDriver)

The super class (TestMyDriver) is a TestCase, meaning:

class TestMyDriver(test.TestCase):

the super class has an attribute named driver that basically is sort of a mock of the tested driver and it declared as follows:

self.driver = mocks.MyDriver()

now In my (TestInitializeConnection) I want to implement the following test:

def test_initialize_connection(self):
    self.driver.initialize_connection(self.volume, self.connector)

Somewhere in the code of the function initialize_connection, there is a private method that is being called

specs = self._get_specs(volume)

and I want to make my test to tell this call of _get_specs(volume) to return a specific value, for example a dictionary with the value: {'iops': 100, 'bandwith': 200}

What is the best way of doing so?

Thanks, Matan

slashms
  • 928
  • 9
  • 26
  • 1
    You can follow @Dan's suggestion but... my rule is avoid to mock private method. What `_get_spec()` do? Is there a way to obtain the same result by mocking some collaborators? Is it possible to make a safe refactoring to help these kind of tests? More use to mock private methods and attributes and more your code become tangled to tests -> refactoring become very hard and you are loosing the ability to change your code that is the best advantage that tests give to you. – Michele d'Amico Dec 16 '15 at 20:35

1 Answers1

0

Just mock it out.

def test_initialize_connection(self):
  with mock.patch.object(
      self.driver, 
      '_get_specs', 
      return_value='your_fake_value') as mock_specs:
    # Do something with self.driver
Dan
  • 1,874
  • 1
  • 16
  • 21
  • Thanks Dan,Is there anyway to use the @patch annotation in order to avoid the with? – slashms Dec 16 '15 at 21:28
  • Just use `self.driver._get_specs = mock.MagicMock()` followed by `self.driver._get_specs.return_value = 'fake_value'` – Dan Dec 16 '15 at 21:42