当前位置: 代码迷 >> 综合 >> python 测试类的封装
  详细解决方案

python 测试类的封装

热度:99   发布时间:2024-01-28 05:15:38.0

1.嵌入测试

测试的数据与代码嵌在一起写在注释中

from doctest import testmod
def test_func(array):""" 测试的输入信息写在注释中,>>>表示输入 输出在下一行,调用testmod()会检查输入与注释中的输出是否相同>>> print(test_func([20, 30, 70]))40.0"""return sum(array) / len(array)
testmod()   # 自动验证嵌入测试

2.unittest模块

使用unittest进行测试需要继承模块的TestCase类

def test_func(array):"""需要测试的方法:param values: []:return: 返回数据的平均值"""return sum(array) / len(array)from unittest import TestCase, mainclass MyTest(TestCase):  # 继承测试类def test(self):  # 编写测试方法self.assertRaises(ZeroDivisionError, test_func, [])  # 异常测试,输入参数->异常类,测试函数,输入参数self.assertRaises(TypeError, test_func, 20, 30, 70)  # 异常测试,输入参数->异常类,测试函数,输入参数...self.assertEqual(test_func([70, 80, 90]), 80.1)  # 等值测试,输入参数 -> 参数B ,参数B
main()  # 开始测试

 

  相关解决方案