【问题标题】:Python unit test failure: should raise value error but notPython单元测试失败:应该引发值错误但不是
【发布时间】:2017-11-20 20:24:12
【问题描述】:

这是我尝试学习单元测试的代码。 为测试目的创建一个学生类。测试无效的测试用例不断失败。

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。函数中的代码确实会引发该异常,但随后会捕获并处理它。整个函数不会引发异常。
  • 谢谢!知道了。也感谢您帮助编辑我的问题。

标签: python unit-testing raiserror


【解决方案1】:

您在函数中捕获了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

【讨论】:

  • 是的,我删除了 try/except 块并且单元测试用例通过了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2021-05-08
  • 2023-01-22
  • 1970-01-01
相关资源
最近更新 更多