一、前言
python的两个单元测试包分别是 doctest 和 unittest,这两个包的使用起来各有长处,适用于不同的场景
- doctest:直接写在方法体中,利用了 python 动态语言的特性,书写方式简单明了,前提是项目不要太大,如果项目复杂代码量大,再加上写在方法体中的单元测试,整体就会看起来有些臃肿,因此 doctest 适用于代码量不大的普通项目
- unittest:一般写在独立文件中,与 spring 的单元测试有点像,项目结构清晰,不过简单项目中测试一些小功能的话实属dark不必了
二、实现
先写一个待测试的方法
1
2
|
def add(num1, num2): return num1 + num2 |
1.doctest
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
def add(num1, num2): """ 直接写在待测方法中 >>> add(14, 5) 19 >>> add(14, 5) > 1 True >>> add(20, 30, 70) Traceback (most recent call last): ... TypeError: add() takes 2 positional arguments but 3 were given """ return num1 + num2 if __name__ = = "__main__" : import doctest doctest.testmod() |
运行上面的代码什么都不会输出,因为预测结果全部正确,只有在预测结果错误的时候才会给提示
ps:
- add(14, 5) 为测试方法,19 为预测结果
- add(14, 5) > 1 为测试方法,True 为预测结果
- add(20, 30, 70) 为测试方法,Traceback (most recent call last): 为异常抛出的第一句话【错误原因】,TypeError: add() takes 2 positional arguments but 3 were given 为异常抛出的最后一句话【异常类型:解释说明】,中间三个点省略了异常中的文件路径信息
2.unittest
1
2
3
4
5
6
7
8
9
10
11
|
import unittest # 引入上面的待测试方法 from src.main.add import add class TestStatisticalFunctions(unittest.TestCase): def test_add( self ): self .assertEqual(add( 14 , 5 ), 19 ) # 断言 add(14, 5) 的结果为 19 self .assertTrue(add( 14 , 5 ) > 1 , True ) # 断言 add(14, 5) > 1 的结果为 True with self .assertRaises(TypeError): # 断言 add(20, 30, 70) 抛出 TypeError 异常 add( 20 , 30 , 70 ) if __name__ = = '__main__' : unittest.main() |
同样,运行上面的代码什么都不会输出,因为预测结果全部正确,只有在预测结果错误的时候才会给提示
到此这篇关于Python单元测试的两种写法的文章就介绍到这了,更多相关Python单元测试内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/weixin_43721000/article/details/125649461