Python单元测试入门_unittest使用

3次阅读

python unittest是标准库单元测试框架,需继承testcase、方法名以test_开头,用assertequal等断言;支持setup/teardown、跳过测试和预期失败装饰器,开箱即用。

Python单元测试入门_unittest使用

Python自带的unittest是标准库中最常用的单元测试框架,语法清晰、功能完整,适合初学者快速上手。它基于Java的junit设计,支持测试用例组织、断言、前置/后置处理等核心能力。

如何写一个最简单的测试用例

每个测试类需继承unittest.TestCase,每个以test_开头的方法会被自动识别为测试用例:

  • 测试方法名必须以test_开头,否则不会被运行
  • 使用self.assertEqual()等断言方法检查结果是否符合预期
  • 测试失败时会显示具体差异,便于定位问题

示例:

import unittest  def add(a, b):     return a + b  class TestAdd(unittest.TestCase):     def test_add_positive(self):         self.assertEqual(add(2, 3), 5)      def test_add_negative(self):         self.assertEqual(add(-1, -1), -2)

运行测试的几种常用方式

无需额外安装,直接通过命令行或Python模块调用即可执行:

立即学习Python免费学习笔记(深入)”;

  • 在终端中运行:python -m unittest test_module.py
  • 在脚本末尾添加:if __name__ == '__main__': unittest.main()
  • 运行单个测试方法:python -m unittest test_module.TestAdd.test_add_positive

-v参数可查看详细输出,如python -m unittest -v test_module.py

设置和清理:setUp与tearDown

当多个测试需要共用资源(如临时文件、数据库连接)时,可用setUp()tearDown()统一管理:

  • setUp()在每个测试方法执行前调用,用于准备环境
  • tearDown()在每个测试方法执行后调用,用于清理资源
  • 即使测试失败,tearDown()仍会执行,确保环境干净

例如:

class TestFileOps(unittest.TestCase):     def setUp(self):         self.temp_file = 'test_temp.txt'          def tearDown(self):         if os.path.exists(self.temp_file):             os.remove(self.temp_file)          def test_write_then_read(self):         with open(self.temp_file, 'w') as f:             f.write('hello')         with open(self.temp_file) as f:             self.assertEqual(f.read(), 'hello')

跳过测试和标记预期失败

实际开发中常需临时跳过某些测试,或标记尚未修复但已知会失败的用例:

  • @unittest.skip('原因'):无条件跳过
  • @unittest.skipIf(condition, '原因'):满足条件时跳过
  • @unittest.skipUnless(condition, '原因'):不满足条件时跳过
  • @unittest.expectedFailure:标记为“预期失败”,若通过则视为异常

这些装饰器可加在测试方法或整个测试类上,方便控制测试行为。

掌握以上要点,就能覆盖日常80%以上的单元测试需求。不需要复杂配置,也不依赖第三方包,开箱即用。

text=ZqhQzanResources