我正在尝试 运行 使用 python 进行单元测试。但是,当我尝试 运行 下面的代码时,即使我已经处理了异常,我也会出错

I am trying to run unittest using python. But, when I try to run the below code, I get error even though I have handled the exception

import unittest
import math

class Circle:
    def __init__(self, radius):
        self.radius = radius
        # Define the initialization method below
        try:
            if not isinstance(radius, (int, float)):
                raise TypeError
        except TypeError:
            print("radius must be a number")
        try:
            if radius in range(0, 1001):
                raise ValueError
        except ValueError:
            print("radius must be between 0 and 1000 inclusive")

    def area(self):
        return round(math.pi * self.radius ** 2, 2)

    def circumference(self):
        return round(2 * math.pi * self.radius)


class TestCircleCreation(unittest.TestCase):
    def test_creating_circle_with_numeric_radius(self):
        # Define a circle 'c1' with radius 2.5 and check if
        # the value of c1.radius equal to 2.5 or not
        c1 = Circle(2.5)
        self.assertEqual(2.5, c1.radius)

    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"
        c2 = Circle(-2.5)
        self.assertRaises(ValueError, c2)

    def test_creating_circle_with_greaterthan_radius(self):
        # Try Defining a circle 'c' with radius 1000.1 and see
        # if it raises a ValueError with the message
        # "radius must be between 0 and 1000 inclusive"
        c3 = Circle(1000.1)
        self.assertRaises(ValueError, c3)

    def test_creating_circle_with_nonnumeric_radius(self):
        # Try Defining a circle 'c' with radius 'hello' and see
        # if it raises a TypeError with the message
        # "radius must be a number"
        c4 = Circle("hello")
        self.assertRaises(TypeError, c4)

assertRaises expects a function for it's second parameter. 你正在传递一个 Circle 对象,它试图将其作为函数调用;这是导致该错误的原因。

我想你的意思是这样的:

self.assertRaises(ValueError, lambda: Circle(-2.5))

然后对其他案例进行类似的更改。

这将对 Circle 构造函数的调用包装在 lambda 函数中,因此 assertRaises 可以根据需要调用构造函数。


这仍然会失败,因为您正在使用 try 来捕获 assertRaises 正在寻找的 ValueErrorTypeError。如果您希望抛出异常,请不要在内部捕获它们。