Python单元测试框架unittest简明使用实例

(编辑:jimmy 日期: 2025/3/1 浏览:2)

测试步骤
1. 导入unittest模块
import unittest

2. 编写测试的类继承unittest.TestCase
class Tester(unittest.TestCase)

3. 编写测试的方法必须以test开头
def test_add(self)
def test_sub(self)

4.使用TestCase class提供的方法测试功能点

Python单元测试框架unittest简明使用实例

5.调用unittest.main()方法运行所有以test开头的方法
复制代码 代码如下:
if __name__ == '__main__':
unittest.main()

实例如下
被测试类

复制代码 代码如下:
#!/usr/bin/python
#coding=utf-8

class Computer(object):
 @staticmethod
 def add(a, b):
  return a + b;
 
 @staticmethod
 def sub(a, b):
  return a - b;<strong> </strong>

测试类

复制代码 代码如下:
#!/usr/bin/python
#coding=utf-8
import unittest
from Testee import Computer

class Tester(unittest.TestCase): 
 def test_add(self):
  self.assertEqual(Computer.add(2, 3), 5, "test add function")
  
 def test_sub(self):
  self.assertEqual(Computer.sub(5, 1), 4, "test sub function") 

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

"codetitle">复制代码 代码如下:
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OK

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。