这是我的代码试图学习单元测试。 创建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
上面的来自运行结果。
有没有人可以帮我弄清楚为什么我有这个失败,而我认为我在那里放了正确的'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()
由于
答案 0 :(得分:2)
您正在捕捉函数内的ValueError
。您需要删除函数中的try
/ except
块,或者在内部执行任何操作后重新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