pythonunit-testingraiserror

Python unit test failure: should raise value error but not


Here is my code trying to learn unit testing. Create a Student class for the purpose of testing. The test invalid test case constantly failed.

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

above is from running result.

Could anyone help me to figure out why I have this failure while I think I have put the right 'Raise Error' code there....

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()

Thanks


Solution

  • You're catching the ValueError inside the function. You need to either remove the try/except block in the function or re-raise it after doing whatever you want inside:

    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