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

Python unittest未执行问题:TDD实践中测试用例运行异常

我一眼就瞅出问题所在了——你的测试用例根本没被unittest框架识别到,还有几处小细节得调整下,咱们一步步来修复:

1. 测试类必须继承unittest.TestCase

这是核心问题!你的TranspilerTDD类没有继承unittest的测试基类,unittest只会把**继承自TestCase**的类里以test_开头的方法当作测试用例。修改类定义:

class TranspilerTDD(unittest.TestCase):

2. 正确调用transpile函数

你导入了transpiler模块,但直接写transpile(source)会找不到这个函数(除非你用from transpiler import transpile)。两种解决方式选一个就行:

  • 方式一:用模块名调用函数
    result = transpiler.transpile(source)
    
  • 方式二:直接导入函数
    from transpiler import transpile
    

3. 去掉不必要的分号

Python里语句结尾不需要加分号,虽然不影响运行,但不符合PEP8编码规范,建议删掉:

result = transpiler.transpile(source)  # 去掉末尾的分号

修正后的完整测试代码

import unittest
import transpiler

class TranspilerTDD(unittest.TestCase):
    def test_adds_encoding(self):
        source = ""
        result = transpiler.transpile(source)
        expected = "#coding: utf-8\n"
        self.assertEqual(result, expected)

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

现在再运行python test_transpiler.py,unittest就能正确识别并执行你的测试用例了。之前显示Ran 0 tests就是因为框架找不到符合要求的测试类,继承TestCase后就能正常识别啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:57:29