1

I am trying to use unittest with unittest.mock to do some tests in my application.

I have two classes MainClass and Caller. I would like to test main class with a double Caller. This is in short what I have:

class MainClass:

 def __init__(self, caller):
   self.caller = caller

 def some_function(self):
   self.caller.function1()
   blab = self.caller.function2()

class Caller:

 # some functions non of which should be accessed in tests


class CallerMock:
  def __init__(self):
   self.items = []

  def function1(self):
   pass

  def function2(self):
    return items

In the test I do:

class TestMainFunction(unittest.TestCase):

    def setUp(self):
        self.mock = MagicMock(wraps=CallerMock())
        self.main_class = MainClass(self.mock)

    def test(self):
        # self.main_class.caller.items = items
        # self.mock.items = items
        # self.mock.function2.return_value = items
        self.main_class.some_functions()
        # non of the above change the return value of function2

However the problem is that non of the commented lines actually change the return value of my function2. How can I achieve this?

I would be also happy with a solution where I don't need the double and all the functions of the Caller would return None and I would have to specify the return values of functions in particular tests.

Ela
  • 3,142
  • 6
  • 25
  • 40

1 Answers1

0

You could just mock the Caller, and patch the call() method. That way, you won't need a double:

def setUp(self):
    self.mocked_caller = mock.Mock(spec=Caller)
    self.mocked_caller.call.return_value = items
    self.main_class = MainClass(self.mocked_caller)

def test(self):
    self.main_class.some_function()
    self.assertTrue(self.mocked_caller.called)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • this doesn't resolve it as then all the functions of Mock return Mock object. I should have specified that the run function calls many of the Callers functions and so I need to specify the default return values for all of them – Ela Mar 18 '16 at 20:34
  • @Ela You can then set `return_value` for all the used functions. – Rohit Jain Mar 19 '16 at 02:59