【发布时间】:2019-07-28 18:48:10
【问题描述】:
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)
【问题讨论】:
-
什么错误?你正在捕捉
ValueErrors,但你也断言它们会被抛出。我猜你会收到AssertionErrors?你为什么要抛出try阻止try捕获的相同异常? -
我得到了 'TypeError: 'Circle' object is not callable' 对于上述两个测试:'test_creating_circle_with_negative_radius' 和 'test_creating_circle_with_greaterthan_radius'。
-
以后,请格式化您的代码并添加足够的错误描述。让别人难以帮助你并不是获得帮助的好方法。
-
这是我在 Stack 上提出的第一个问题,因为我是编程新手。以后我会尝试更清楚地表达我的问题。
标签: python-3.x exception python-unittest