首页 > 解决方案 > 为什么这段代码会引发 AssertionError?

问题描述

这是代码。

# mean_var_std.py

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

这是测试。

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)
----------------------------------------------------------------------
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: ValueError not raised by calculate

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

FAILED (failures=1)

输出表明代码没有引发 ValueError,但从代码中我们可以清楚地看到代码引发了 ValueError。为什么我的代码仍然未能通过单元测试?

标签: python-3.xunit-testingdebugging

解决方案


这是因为您在测试接收到 ValueError 之前捕获了它。删除try catch,它应该可以工作

# mean_var_std.py

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

推荐阅读