3秒钟unittest入门使用

匿名 (未验证) 提交于 2019-12-02 23:59:01

一:unittest跑起来

unittest使用,具体使用方式可以查看unittest官网,以下简单做个介绍,在工作中使用最多的

#
第一步:

创建unittest类,且一定要继承unittest.TestCase

class MytestDemo(unittest.TestCase): 

 

第二步:

创建你要运行的方法,且一定是用test开头,unittest是检测test开头就会认为有运行方法,如果不用test开头就不用

def test_show():      print(运行成功) 

  

第三步:

运行,使用main入口

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

好了至此,你就已经是使用unittest框架了

但是这样其实在工作中不能满足我们,我们在执行测试方法前都会做一些前置条件,依赖于unittest中的几个方法

二、增加初始化的方法,

在类中,添加,setUp (前置方法,每次运行方法时就会运行),tearDown(运行完后的后置处理,每个方法运行时就会运行)setUpClass(第一次运行类时,开始运行)

#coding=utf-8 import unittest import requests  class MytestDemo(unittest.TestCase):     '''     http: // www.kuaidi100.com / query?type = 快递公司代号 & postid = 快递单号     测试用例     ps:快递公司编码:申通 = "shentong"     EMS = "ems"     顺丰 = "shunfeng"     圆通 = "yuantong"     中通 = "zhongtong"     韵达 = "yunda"     天天 = "tiantian"     汇通 = "huitongkuaidi"     全峰 = "quanfengkuaidi"     德邦 = "debangwuliu"     宅急送 = "zhaijisong"     number=1     '''     @classmethod     def setUpClass(cls):         print("第一次运行类时调用")       def setUp(self):         self.url = "http://www.kuaidi100.com/query"         self.headers1 = { 'Connection': 'keep-alive'}      def tearDown(self):         print("后面收尾")      def test_yuantong(self):         url=self.url+"?type=yuantong&postid=11111111111"         result=requests.get(url=url,headers=self.headers1)         print(result.url)         print(result.text)      def test_tiantian(self):         data = "type=tiantian&postid=11111111111"         result = requests.get(url=self.url, params=data,headers=self.headers1 )         print("************")         print(result.url)         print(result.text) if __name__ == '__main__':     unittest.main() 

  我使用了两个方法,一个圆通,一个天天,self.url就是获取在setUp中的url,显示内容:

3.1 单个类运行

在类的方法旁边,使用运行,运行单个方法

3.2: 整体运行

在main中运行,

在运行方式中,unittest.main(),还有几种方式表示

使用unittest.TestSuite()集合方式运行,这种方式可以在单个类中运行,也可以在运行多个文件

if __name__ == '__main__':     #unittest.main()     suite = unittest.TestSuite()     suite1 = unittest.TestLoader().loadTestsFromTestCase(MytestDemo)     # 增加文件     suite.addTest(suite1)     unittest.TextTestRunner().run(suite1)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!