背景:单元测试初学者在这里。尝试在编写代码时养成测试驱动开发的习惯。因此,我制作了一个简单的奇数或偶数计算器,并想测试这个简单程序的每个角度。
简单奇偶数检查器的码
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)
检查奇数条件的单位测试是工作的
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是== to True self.assertEqual(get_odd_even(7), True, "Should read this as an odd number")
发布于 2020-11-04 16:54:00
assertEqual
将检查其前两个参数是否相等。这意味着它正在测试get_odd_even
的返回值是否与True
相同。但是,get_odd_even
函数不返回值。这就是你得到AssertionError: None != True
的原因。您应该修改get_odd_even
以返回字符串,而不是打印字符串,或者查看asserting output。
https://stackoverflow.com/questions/64684260
复制相似问题