Python 3.x 基本If语句单元测试

Python 3.x 基本If语句单元测试,python-3.x,python-unittest,Python 3.x,Python Unittest,背景:这里是单元测试初学者。在编写代码时,尝试养成测试驱动开发的习惯。所以我做了一个简单的奇数或偶数计算器,想测试这个简单程序的每个角度 简单奇数/偶数检查器的代码 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

背景:这里是单元测试初学者。在编写代码时,尝试养成测试驱动开发的习惯。所以我做了一个简单的奇数或偶数计算器,想测试这个简单程序的每个角度

简单奇数/偶数检查器的代码

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正在工作

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

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)
我也尝试过:


假设由于if语句正在寻找一个布尔响应,我断言我的参数7是==到True
self。assertEqual(get_odd_偶数(7),True,“应该将其读为奇数”)
assertEqual
将检查其前两个参数是否相等。这意味着它正在测试
get\u odd\u偶
的返回值是否与
True
相同。但是,
get\u odd\u偶
函数不返回值。这就是为什么您会得到
AssertionError:None!=正确
。您应该改变
获取奇偶
以返回字符串,而不是打印字符串,或者查看。

啊!这么简单。我不知道您也可以
返回“这样的字符串”
。太棒了,谢谢你!