AssertionError: ValueError not raised

AssertionError: ValueError not raised

init class 异常不会引发 assetRaises()

识别的异常

当我为 class 单独创建一个实例时,定义的异常被正确打印

import unittest

class Circle:
    def __init__(self, radius):
        # Define the initialization method below
        self.radius = radius
        try :
          if  radius < 0 or radius > 1000 : raise ValueError
        except ValueError :
          print("radius must be between 0 and 1000 inclusive")

class TestCircleCreation(unittest.TestCase):
    def test_creating_circle_with_negative_radius(self):
        # Try Defining a circle 'c' with radius -2.5 and see 
        # if it raises a ValueError with the message
        # "radius must be between 0 and 1000 inclusive"
        with self.assertRaises(ValueError) as e:
            c = Circle(-2.5)
        self.assertEqual(str(e.exception),"radius must be between 0 and 1000 inclusive")

给出错误:

AssertionError: ValueError not raised

assertRaises 仅测试上下文管理器中是否抛出异常。您捕获了异常并且没有重新引发它,所以它永远不会被 unittest 看到。

引发异常然后立即捕获它也没有多大意义。 相反:

class Circle:

    def __init__(self, radius):
        # Define the initialization method below
        self.radius = radius
        if radius < 0 or radius > 1000:
            raise ValueError("radius must be between 0 and 1000 inclusive")

您正在捕获 __init__ 中的异常。您的测试断言异常是从 __init__ out 抛出的,而不是在其中捕获的。像这样:

def __init__(self, radius):
    if radius < 0 or radius > 1000:
        raise ValueError("radius must be between 0 and 1000 inclusive")
    self.radius = radius