You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pytest对实例方法getter列表进行参数化测试?

问题描述

我有一个包含多个getter方法的类:

class ExampleClass:
  def __init__(self):
    # 实现省略

  def getter1(self):
    # 实现省略
  
  def getter2(self):
    # 实现省略

我希望编写一个单元测试,对所有getter方法进行参数化测试(本例中它们应返回相同结果)。
我想采用如下实现方式(注:原代码中bid应为inst,已修正笔误):

import pytest
from pytest import raises

@pytest.mark.parametrize('getter_method', ['getter1', 'getter2'])
def test_exampleclass_getters(getter_method):
    inst = ExampleClass()
    with raises(ValueError):
        getattr(inst, getter_method)(OVN_END_DT)

但我了解到使用getattr属于不良实践,通常应避免,不过我觉得在此场景下是可行的。如果不可行,还有哪些方法可以实现需求?

解决方案

关于getattr在该场景的合理性

在参数化测试多个同类方法的场景下,用getattr完全可行且合理,算不上不良实践。这种写法简洁直观,能避免重复编写几乎完全相同的测试代码,符合DRY原则。只要你确保参数化的方法名都是类中真实存在的,就不会有太大问题。

替代实现方法

如果确实想规避getattr,可以参考以下几种方式:

1. 直接参数化方法对象

不用传递方法名字符串,直接把方法本身作为参数传入:

import pytest
from pytest import raises

@pytest.mark.parametrize('getter_method', [ExampleClass.getter1, ExampleClass.getter2])
def test_exampleclass_getters(getter_method):
    inst = ExampleClass()
    with raises(ValueError):
        getter_method(inst, OVN_END_DT)

这种方式直接操作方法对象,无需字符串查找,类型检查更严格,也能避免方法名拼写错误的风险。

2. 生成独立测试函数

如果需要测试的getter方法很多,可以写个辅助函数生成单独的测试用例:

import pytest
from pytest import raises

def create_getter_test(getter_method):
    def test():
        inst = ExampleClass()
        with raises(ValueError):
            getattr(inst, getter_method)(OVN_END_DT)
    return test

# 为每个getter生成独立测试函数
for getter in ['getter1', 'getter2']:
    globals()[f'test_exampleclass_{getter}'] = create_getter_test(getter)

这种方式会生成多个独立的测试函数,在测试报告中能分别看到每个方法的测试结果,适合需要逐个追踪每个getter测试状态的场景。

3. 结合pytest fixture优化

如果测试中需要重复创建ExampleClass实例,可以用fixture来复用实例创建逻辑:

import pytest
from pytest import raises

@pytest.fixture
def example_instance():
    return ExampleClass()

@pytest.mark.parametrize('getter_method', [ExampleClass.getter1, ExampleClass.getter2])
def test_exampleclass_getters(getter_method, example_instance):
    with raises(ValueError):
        getter_method(example_instance, OVN_END_DT)

这种写法让代码更模块化,实例创建逻辑的复用性更高。

内容的提问来源于stack exchange,提问作者roulette01

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 08:31:03