Nie Selam
Nie Selam

Reputation: 1451

testing a method with two input() in console app

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.

Upvotes: 0

Views: 35

Answers (1)

Kevin
Kevin

Reputation: 76254

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()

Upvotes: 1

Related Questions