3秒钟unittest入门使用

一:unittest跑起来

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

#
第一步:

建立unittest类,且必定要继承unittest.TestCase框架

class MytestDemo(unittest.TestCase):

 

第二步:

建立你要运行的方法,且必定是用test开头,unittest是检测test开头就会认为有运行方法,若是不用test开头就不用
post

def test_show():

    print(运行成功)

  

第三步:

运行,使用main入口
测试

if __name__ == '__main__':

    unittest.main()

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

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

 

2、增长初始化的方法,

 

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

#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,显示内容:spa

 

 3、运行

3.1 单个类运行

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

 

3.2: 总体运行

在main中运行,blog

 

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

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

 

 

 

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

 

 针对TestLoader运行方式有几种,类名,文件名,运行方法名,后续在写一篇

相关文章
相关标签/搜索