Python语言异常处理测试过程解析语言异常处理测试过程解析
主要介绍了Python语言异常处理测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有
一定的参考学习价值,需要的朋友可以参考下
这篇文章主要介绍了Python语言异常处理测试过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定
的参考学习价值,需要的朋友可以参考下
(一)异常处理
1.捕获所有异常
try:
x = 5 / 0
except:
print('程序有错误')
2.捕获特定异常
try:
x = 5 / 0
except ZeroDivisionError as e:
print('不能为0',e)
except:
print('其他错误')
else:
print('没有错误')
finally:
print('关闭资源')
3.手动抛出异常
def method():
raise NotImplementedError('该方法还未被实现')
(二)测试
使用Python自带的unittest模块
example 1:测试某个函数
import unittest
from example import get_formatted_name
class NameTestCase(unittest.TestCase):
def test_title_name(self):
formatted_name = get_formatted_name('tom','lee')
self.assertEqual(formatted_name,'Tom Lee')
if __name__ == '__main__':
unittest.main()
example 2:测试某个类
class Coder:
def __init__(self,name):
self.name = name
self.skills = []
def mastering_skill(self,skill):
self.skills.append(skill)
def show_skills(self):
print('掌握技能:')
for skill in self.skills:
print('-',skill)
import unittest
from coder import Coder
class CoderTestCase(unittest.TestCase):
def setUp(self):
self.c = Coder('Tom')
self.c.mastering_skill('Python')
self.c.mastering_skill('Java')
def test_skill_in(self):
self.assertIn("Python",self.c.skills)
评论0
最新资源