为什么代码未通过单元测试?

时间:2020-08-30 17:40:19

标签: python unit-testing

这是代码:

# mean_var-_std.py
def calculate(list):
    if len(list) < 9:
        print("List must contain nine numbers.")
        raise ValueError
    else:
        return 0

这是单元测试:

import unittest
import mean_var_std


# the test case
class UnitTests(unittest.TestCase):
    def test_calculate_with_few_digits(self):
        self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])

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

这是我得到的错误:

F
======================================================================
FAIL: test_calculate_with_few_digits (test_module.UnitTests)
----------------------------------------------------------------------
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/runner/fcc-mean-var-std-2/test_module.py", line 8, in test_calculate_with_few_digits
    self.assertRaisesRegex(ValueError, "List must contain nine numbers.", mean_var_std.calculate, [2,6,2,8,4,0,1,])
AssertionError: "List must contain nine numbers." does not match ""

----------------------------------------------------------------------
Ran 1 test in 0.004s

FAILED (failures=1)

我不明白AssertionError: "List must contain nine numbers." does not match ""是什么意思。我怎么解决这个问题?预先感谢。

2 个答案:

答案 0 :(得分:2)

您的函数将引发错误,而不会显示错误消息。它还会打印一条消息,但这是无关的(通常被视为不良做法)。

删除print语句,并通过错误消息引发错误以修复单元测试失败:

def calculate(list):
    if len(list) < 9:
        raise ValueError("List must contain nine numbers.")
    else:
        return 0

答案 1 :(得分:0)

这是代码中的一个小修改。

def calculate(list):
    if len(list) < 9:
        print("List must contain nine numbers.")
        raise ValueError("List must contain nine numbers.")
    else:
        return 0

由于您要查找ValueError,因此单元测试不会查看您的打印语句。