0
def function(n):

    if n % 2 != 0:
        print('weird')
    elif n % 2 == 0 and n in range(2, 5):
        print('not weird')
    elif n % 2 == 0 and n in range(6, 20):
        print('weird')
    elif n % 2 == 0 and n > 20:
        print('not weird')
    return n

# while True:
#     n = int(input('enter the number: '))
#     function(n)
import unittest
class Test_function(unittest.TestCase):
    def test_function(self):
        self.assertEqual(function(2), 'not weird')

I'm trying to test the code while executing the code nothing is showing in output. This is the way of writing code to test code? can anyone suggest how to write unit test code?

  • Note that best practice is : the method should return a string, and the caller decide what to do : in execution "print it", in test "test it", that helps – azro Jan 19 '22 at 07:23
  • @arzro I think you didn't explain clearly your comment is not related to my code at all... I'm asking how to test my code – user17821553 Jan 19 '22 at 08:41
  • See the duplicate link for how to test your code – azro Jan 19 '22 at 18:10
  • then my comment is completely related to your code : the good practtice would be to RETURN the string and not printing it, then the main code would print, and the test would check its value – azro Jan 19 '22 at 18:11
  • @azro I don't understand that duplicate link, Can you explain please to me how to test code using my code for example? I search google it's all simple code examples are there. – user17821553 Jan 20 '22 at 05:06
  • What don't you understand ? Use the same code, then `assertEqual(capturedOutput.getvalue(), "not weird")` – azro Jan 20 '22 at 07:08

0 Answers0