【问题标题】:Basic If Statement Unittesting基本 If 语句单元测试
【发布时间】:2020-11-04 16:46:57
【问题描述】:

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

简单奇偶数检查器代码

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 是 == 到 True self.assertEqual(get_odd_even(7), True, "Should read this as an odd number")

【问题讨论】:

    标签: python-3.x python-unittest


    【解决方案1】:

    assertEqual 将检查其前两个参数是否相等。这意味着它正在测试get_odd_even 的返回值是否与True 相同。但是,您的 get_odd_even 函数不返回值。这就是您收到AssertionError: None != True 的原因。您应该更改get_odd_even 以返回字符串而不是打印它们,或者查看asserting output。

    【讨论】:

    • 啊!很简单。我也没意识到你也可以return "a string like this"。太棒了,谢谢你!
    猜你喜欢
    • 1970-01-01
    • 2016-08-16
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-04
    • 2018-10-31
    • 2021-06-10
    相关资源
    最近更新 更多