请设计一个测试用例,用于测试Python中一个类的继承和多态性,确保其行为符合预期。
# 定义一个基类
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现此方法")
# 定义两个子类,继承自Animal并实现speak方法
class Dog(Animal):
def speak(self):
return f"{self.name} 说: 汪汪!"
class Cat(Animal):
def speak(self):
return f"{self.name} 说: 喵喵!"
# 测试用例
import unittest
class TestAnimalInheritance(unittest.TestCase):
def test_dog_speak(self):
"""测试Dog类的speak方法"""
dog = Dog("小黑")
self.assertEqual(dog.speak(), "小黑 说: 汪汪!")
def test_cat_speak(self):
"""测试Cat类的speak方法"""
cat = Cat("小白")
self.assertEqual(cat.speak(), "小白 说: 喵喵!")
def test_polymorphism(self):
"""测试多态性"""
animals = [Dog("大黄"), Cat("小花")]
expected_outputs = ["大黄 说: 汪汪!", "小花 说: 喵喵!"]
actual_outputs = [animal.speak() for animal in animals]
self.assertListEqual(expected_outputs, actual_outputs)
def test_abstract_method(self):
"""测试基类的抽象方法是否抛出异常"""
animal = Animal("抽象动物")
with self.assertRaises(NotImplementedError):
animal.speak()
# 运行测试
if __name__ == "__main__":
unittest.main()
详细说明
-
基类设计:
Animal是基类,定义了一个抽象方法speak,子类必须实现此方法。通过raise NotImplementedError强制要求子类重写该方法。
-
子类实现:
Dog和Cat继承自Animal,分别实现了speak方法,返回不同的字符串。这展示了继承和多态的特性。
-
测试用例:
test_dog_speak和test_cat_speak分别测试Dog和Cat类的speak方法,确保其行为符合预期。test_polymorphism展示多态性:通过一个包含Dog和Cat对象的列表,调用speak方法时,会根据对象的实际类型执行对应的方法。test_abstract_method测试基类的抽象方法是否抛出了预期的异常。
-
运行测试:
- 使用
unittest框架运行测试,确保所有测试用例通过。
- 使用
设计要点
- 继承:子类继承基类的方法和属性,并可扩展或重写方法。
- 多态:同一方法在不同子类中有不同的实现,运行时根据对象类型动态调用。
- 抽象方法:基类通过抛出异常强制子类实现特定方法,确保设计的一致性。
扩展性
- 可以添加更多子类(如
Bird)并扩展测试用例,验证设计是否灵活。 - 可通过增加新的抽象方法或属性,进一步测试继承的深度和多态的复杂性。