Python单元测试失败:应引发值错误,但不是
下面是我试图学习单元测试的代码。 为测试目的创建一个学生类。测试无效的测试用例经常失败Python单元测试失败:应引发值错误,但不是,python,unit-testing,raiserror,Python,Unit Testing,Raiserror,下面是我试图学习单元测试的代码。 为测试目的创建一个学生类。测试无效的测试用例经常失败 FAIL: test_invalid (__main__.TestStudent) ---------------------------------------------------------------------- Traceback (most recent call last): File "mystudent.py", line 46, in test_invalid s1.get
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
以上是运行结果
有谁能帮我弄清楚为什么我会出现这种故障,而我认为我已经在那里输入了正确的“Raise Error”代码
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()
导入单元测试
班级学生(对象):
定义初始(自我、姓名、分数):
self.name=名称
self.score=分数
def get_等级(自我):
尝试:
如果self.score>=60且self.score<80:
返回“B”
如果self.score>=80,self.score=0,self.score=100:
raise VALUERROR('分数值无效')
例外情况除外,如e:
打印('值错误!')
类TestStudent(unittest.TestCase):
def测试_无效(自身):
s1=学生(‘鲍勃’,-1)
s2=学生('Bat',101)
使用self.assertRaises(ValueError):
s1.获得(u级)
使用self.assertRaises(ValueError):
s2.获得_等级()
如果uuuu name uuuuuu='\uuuuuuu main\uuuuuuu':
unittest.main()
谢谢您正在捕获函数中的
ValueError
。您需要删除函数中的try
/除外
块,或者在执行任何需要的操作后重新提升它:
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
def获取等级(自身):
尝试:
如果self.score>=60且self.score<80:
返回“B”
如果self.score>=80,self.score=0,self.score=100:
raise VALUERROR('分数值无效')
例外情况除外,如e:
打印('值错误!')
raise#向上传递异常
您的函数不会引发ValueError。函数中的代码确实引发了该异常,但随后捕获并处理该异常。整个函数不会引发异常。谢谢!知道了。谢谢你帮我编辑我的问题。是的,我删除了try/except块,单元测试用例通过了。