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

在Pytest中测试Python私有方法遇报错,该如何正确测试?

如何正确测试Python模块中的私有方法?

问题场景

我在wallets.py模块中定义了一个私有方法:

def __foo():
    return 0

使用如下测试代码test_wallets.py测试时:

from unittest import TestCase
from db.services import wallets

class GetTokenQuantity(TestCase):
    def test_get_token_quantity(self):
        token_quantity = wallets.__foo()

出现错误:

AttributeError: module 'db.services.wallets' has no attribute '_GetTokenQuantity__foo'

解决方法

1. 使用名称修饰后的正确名称调用

Python对模块/类中以双下划线开头的私有成员会自动做名称修饰,模块级的__foo会被改为_模块名__foo,这里模块名是wallets,所以测试代码里应该这样调用:

def test_get_token_quantity(self):
    token_quantity = wallets._wallets__foo()

2. 导入时重命名私有函数

可以在导入时直接把私有函数重命名,避开名称修饰的影响:

from unittest import TestCase
from db.services.wallets import __foo as _foo

class GetTokenQuantity(TestCase):
    def test_get_token_quantity(self):
        token_quantity = _foo()

3. 更合理的实践:调整私有方法定义(推荐)

直接测试私有方法并不符合软件工程最佳实践——私有方法属于模块内部实现细节,应该通过测试依赖它的公共方法来验证逻辑。如果确实需要单独测试,建议把方法改为单下划线开头(_foo),这是Python约定俗成的“私有”标识,不会触发名称修饰,测试时可直接调用:

# wallets.py
def _foo():
    return 0

# test_wallets.py
def test_get_token_quantity(self):
    token_quantity = wallets._foo()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 02:18:17