user13641095
user13641095

Reputation: 107

Basic If Statement Unittesting

Background: Unittesting beginner here. Trying to develop of habit of Test Driven Development when writing code. So I made a simple odd or even number calculator and want to test every angle of this simple program

Code for simple odd/even number checker

def get_odd_even(numb):
    if numb % 4 == 0:
        print("This number is a multiple of 4")
    elif numb % 2 == 0:
        print("This number is even")
    else:
        print("This number is odd")


if __name__ == "__main__":
    numb = int(input("Enter a number: "))
    get_odd_even(numb)

Unittest to check odd number conditional is working

import unittest
from odd_even import get_odd_even


class MyTestCase(unittest.TestCase):
    def test_odd(self):
        self.assertEqual(get_odd_even(7), "This number is odd", "Should read this as an odd number")


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

Traceback

This number is odd
F
======================================================================
FAIL: test_odd (__main__.MyTestCase)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "test_odd_even.py", line 7, in test_odd
    self.assertEqual(get_odd_even(7),True, "Should read this as an odd number")
AssertionError: None != True : Should read this as an odd number

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

What I've Also Attempted:

Assuming since the if statement is looking for a boolean response that I assert my argument of 7 is == to True self.assertEqual(get_odd_even(7), True, "Should read this as an odd number")

Upvotes: 0

Views: 116

Answers (1)

ThisIsAQuestion
ThisIsAQuestion

Reputation: 1967

assertEqual will check if its first two arguments are equal. That means it is testing whether the return value of get_odd_even is the same as True. However, your get_odd_even function does not return a value. That's why you're getting AssertionError: None != True. You should either alter get_odd_even to return strings instead of printing them, or look into asserting output.

Upvotes: 1

Related Questions