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

为何Python unittest的setUp()未触发不存在类的运行时错误?

问题描述

刚接触Python的unittest库,遇到一个疑问:在测试方法中实例化不存在的queue.Queue类时,会触发AttributeError运行时错误;但将该代码移到setUp()方法后,运行测试显示“Ran 0 tests in 0.000s OK”,后续引用self.queue也无错误,想了解这一现象的原因。

初始测试代码

import queue
import unittest

class TestSuite(unittest.TestCase):
    def test_new_queue(self):
        self.queue = queue.Queue()

if __name__ == '__main__':
    unittest.main()

初始代码报错结果

Traceback (most recent call last):
File "[omitted]/test_suite.py", line 6, in test_new_queue
self.queue = queue.Queue()
AttributeError: module 'queue' has no attribute 'Queue'


Ran 1 test in 0.001s

FAILED (errors=1)

修改后的代码

import queue
import unittest

class TestSuite(unittest.TestCase):
    def setUp(self):
        self.queue = queue.Queue()

if __name__ == '__main__':
    unittest.main()

修改后运行结果


Ran 0 tests in 0.000s

OK

原因解析
  • unittest的测试用例识别规则:unittest框架只会自动执行类中以test_开头的方法作为测试用例。修改后的代码里,类中只有setUp方法,没有任何符合命名规则的测试方法,所以框架判定没有需要运行的测试用例,直接输出“Ran 0 tests”的结果。
  • setUp方法的执行逻辑:setUp是unittest的前置初始化方法,只有当类中存在可执行的测试用例时,才会在每个测试用例运行前被调用。修改后的代码没有测试用例,setUp方法根本没被执行,自然不会触发queue.Queue()的AttributeError。
  • 关于“后续引用无错误”的误解:如果后续添加了test_开头的测试方法,在方法里引用self.queue时,setUp会被执行,此时依然会触发AttributeError——之前觉得引用无错误,只是因为那部分代码根本没被运行到而已。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 04:55:30