Python重载unittest.TestCase实现参数化运行时传参异常如何解决
问题根源
Python unittest 框架中 TestCase 类的原生构造方法第一个参数固定为要执行的测试方法名,测试运行器实例化测试类时,会自动将匹配到的测试方法名(你的代码中为test_case)作为第一个参数传入构造函数。
你的代码重写了Fixture类的构造方法,将第一个参数用作接收自定义option,同时将该参数赋值给self.option、并传入父类TestCase的构造方法。此时测试运行器传入的测试方法名test_case会直接覆盖你自定义的option值,最终打印出的自然是方法名而非你预期的one。
解决方法
有两种常用实现方案,推荐优先选择第一种,避免改动TestCase原生构造逻辑:
方案1:通过类属性传递自定义参数
无需重写构造方法,直接在父类定义公共属性,子类赋值自定义值即可:
from unittest import TestCase class Fixture(TestCase): option = None def setUp(self): print(f'\nSetting up option {self.option}') def test_case(self): print(f'Testing option {self.option}') class Runner(Fixture): option = 'one' def case(self): self.test_case()
方案2:保留原生构造参数后新增自定义参数
如果必须通过构造方法动态传参,需要给父类需要的测试方法名参数留位置:
from unittest import TestCase class Fixture(TestCase): # 第一个参数保留为测试方法名,自定义参数放在后面 def __init__(self, methodName='runTest', option=None): self.option = option super().__init__(methodName) def setUp(self): print(f'\nSetting up option {self.option}') def test_case(self): print(f'Testing option {self.option}') class Runner(Fixture): def __init__(self, methodName='runTest'): super().__init__(methodName, option='one') def case(self): self.test_case()
两种方案运行后都可以输出你预期的Setting up option one结果。
内容的提问来源于stack exchange,提问作者mattigSnitram
相关产品推荐
相关产品推荐

