gpt4 book ai didi

Python单元测试失败: should raise value error but not

转载 作者:行者123 更新时间:2023-12-01 02:25:58 26 4
gpt4 key购买 nike

这是我尝试学习单元测试的代码。创建一个 Student 类以进行测试。测试无效的测试用例不断失败。

FAIL: test_invalid (__main__.TestStudent)
----------------------------------------------------------------------
Traceback (most recent call last):
File "mystudent.py", line 46, in test_invalid
s1.get_grade()
AssertionError: ValueError not raised

以上是运行结果。

有人可以帮我弄清楚为什么我会出现此故障,而我认为我已经在那里放置了正确的“引发错误”代码......

import unittest

class Student(object):
def __init__(self, name, score):
self.name = name
self.score = score


def get_grade(self):
try:
if self.score >= 60 and self.score < 80:
return 'B'
if self.score >= 80 and self.score <= 100:
return 'A'
if self.score >= 0 and self.score <60:
return 'C'
if self.score < 0 or self.score > 100:
raise ValueError('Invalid score value')
except Exception as e:
print('Value error!')


class TestStudent(unittest.TestCase):


def test_invalid(self):
s1 = Student('Bob', -1)
s2 = Student('Bat', 101)
with self.assertRaises(ValueError):
s1.get_grade()
with self.assertRaises(ValueError):
s2.get_grade()


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

谢谢

最佳答案

您正在函数内捕获ValueError。您需要删除函数中的 try/ except block ,或者在执行您想要的操作后重新raise它:

def get_grade(self):
try:
if self.score >= 60 and self.score < 80:
return 'B'
if self.score >= 80 and self.score <= 100:
return 'A'
if self.score >= 0 and self.score <60:
return 'C'
if self.score < 0 or self.score > 100:
raise ValueError('Invalid score value')
except Exception as e:
print('Value error!')
raise # Passes the exception up

关于Python单元测试失败: should raise value error but not,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47400424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com