
在使用模板方法模式组织 unittest 测试时,需让子类(Child1/2/3)运行继承的测试方法,同时完全跳过父类(Parent)自身的测试实例化——避免失败、不收集、不执行,且不依赖 python_classes 命名过滤。
在使用模板方法模式组织 unittest 测试时,需让子类(child1/2/3)运行继承的测试方法,同时完全跳过父类(parent)自身的测试实例化——避免失败、不收集、不执行,且不依赖 `python_classes` 命名过滤。
在 pytest 中混合使用 unittest.TestCase 继承与模板方法模式时,一个常见痛点是:父类虽定义了通用测试逻辑(如 test_setup_validation),但它本身不应被实例化或运行;否则会因抽象方法未实现、setUp 缺失或空运行而报错或冗余执行。而直接设置 __test__ = False 或声明为 abc.ABC 会导致子类测试也无法被发现——因为 pytest 的收集器依据 unittest.TestCase 的继承链和可调用性判断测试有效性。
✅ 推荐方案:采用复合继承(Composition via Multiple Inheritance)
核心思想是解除父类与 unittest.TestCase 的直接继承关系,转而将其作为纯逻辑基类,并在子类中按特定顺序多重继承:先继承逻辑父类,再继承 unittest.TestCase。该顺序至关重要——Python 方法解析顺序(MRO)确保 setUp, tearDown 和测试方法能被正确识别,同时 pytest 仅将显式继承 unittest.TestCase 的类视为测试容器。
# 逻辑基类:无继承,仅封装共享行为
class TestTemplate:
def setUp(self):
# 公共初始化逻辑(pytest 会自动调用)
self.shared_resource = "initialized"
def test_common_behavior(self):
assert hasattr(self, "shared_resource")
assert self.shared_resource == "initialized"
def abstract_setup_step(self):
raise NotImplementedError("子类必须实现 abstract_setup_step")
# 子类:按顺序继承 —— 先逻辑基类,后 TestCase
class Child1(TestTemplate, unittest.TestCase):
def abstract_setup_step(self):
self.child_specific = "child1"
def test_child1_only(self):
assert self.child_specific == "child1"
class Child2(TestTemplate, unittest.TestCase):
def abstract_setup_step(self):
self.child_specific = "child2"
def test_child2_only(self):
assert self.child_specific == "child2"✅ 优势:
TestTemplate不会被 pytest 收集(非TestCase子类),Child1/Child2则完整继承测试方法并可正常运行;setUp自动触发,test_common_behavior在每个子类实例中独立执行,零冗余、零失败。
⚠️ 注意事项:
- 若仍需保留
unittest.TestCase继承结构(如遗留代码约束),可退而采用「运行时守卫」方案,但不推荐用于新项目:class Parent(unittest.TestCase): def test_core_logic(self): if type(self) is Parent: # 严格类型检查,非 isinstance self.skipTest("Parent 是抽象基类,不直接运行") # 正常测试逻辑... self.abstract_setup_step() self.assertTrue(True)此方式会使父类测试被收集并标记为
skipped(非failed),但会增加测试总数,且skipTest不适用于setUp中的校验。
? 总结:复合继承是唯一兼顾语义清晰性、pytest 兼容性与零副作用的解决方案。它从根本上分离了“可复用测试逻辑”与“可执行测试容器”的职责,符合单一职责原则,也便于未来迁移到纯 pytest 风格(如 @pytest.fixture + parametrize)。切记继承顺序:class Child(ParentLogic, unittest.TestCase) —— 错误顺序将导致测试无法被识别。

















