0

My console app is simply adding two numbers:

  def add():
    a=int(input('Enter first number '))
    b= int(input('Enter second number '))
    return a + b

how do I unit test the above method? I tried the following but I can't seem to pass two values to it:

import unittest

from unittest.mock import patch


@patch('builtins.input', return_value='2')
@patch('builtins.input', return_value='3')
def test_add(self,  a, b ):
    self.assertEqual(result, 5)

While I don't get the prompts asking for numbers during testing, the tests are failing because both a and b are 2.

Nie Selam
  • 1,343
  • 2
  • 24
  • 56
  • Try this: https://stackoverflow.com/questions/21046717/python-mocking-raw-input-in-unittests – Devesh Kumar Singh Apr 03 '19 at 18:19
  • @DeveshKumarSingh thanks. I actually got the idea of patching from it but it only works for single input()s, I think. Unless I misunderstood something. Am I right? – Nie Selam Apr 03 '19 at 18:21

1 Answers1

1

The side_effect parameter can be used to construct a mock object that returns different values each time it is called. Pass it a list or other iterable containing each of your return values.

You can set this attribute directly,

import unittest
from unittest.mock import patch

def add():
    a=int(input('Enter first number '))
    b= int(input('Enter second number '))
    return a + b

class Tester(unittest.TestCase):
    @patch('builtins.input')
    def test_add(self, input_mock):
        input_mock.side_effect = [2,3]
        result = add()
        self.assertEqual(result, 5)

if __name__ == '__main__':
    unittest.main()

Or specify it in the decorator.

import unittest
from unittest.mock import patch

def add():
    a=int(input('Enter first number '))
    b= int(input('Enter second number '))
    return a + b

class Tester(unittest.TestCase):
    @patch('builtins.input', side_effect=[2,3])
    def test_add(self, input_mock):
        result = add()
        self.assertEqual(result, 5)

if __name__ == '__main__':
    unittest.main()
Kevin
  • 74,910
  • 12
  • 133
  • 166