zoukankan      html  css  js  c++  java
  • 接口测试基础——第6篇unittest模块(三)

    今天是unittest最后一讲,我们解决一下如何只运行一次setUp和tearDown方法以及简单的数据驱动的知识。

    1、只运行一次setUp和tearDown方法

        很简单,只需要把setUp和tearDown分别替换为setUpClass和tearDownClass即可,但是用这两个方法必须加上 @classmethod 修饰

    
    # coding: utf-8
    
    import unittest
    import time
    
    class MyTest(unittest.TestCase):
    
        @classmethod
        def setUpClass(cls):
            print "SetUp"
            time.sleep(2)
    
        @classmethod
        def tearDownClass(cls):
            print "teardown"
            time.sleep(2)
    
        def test01(self):
            print "test01"
    
        def test03(self):
            print "test03"
    
        def test02(self):
            print "test02"
    
    if __name__ == '__main__':
        suite = unittest.TestLoader().loadTestsFromTestCase(MyTest)
        unittest.TextTestRunner(verbosity=2).run(suite)

    上面的代码运行以后,得到的输出便是:

    至于@classmethod是什么意思,大家先不要管,后面在说装饰器的时候我会专门的和大家说。

    2、数据驱动

    unittest里的数据驱动也要用到装饰器的知识,还是直接先记住代码即可:

    # coding: utf-8
    
    import unittest
    import time
    import ddt
    
    info = [{"username": "captain", "password": 123},
            {"username": "warrior", "password": 456}]
    
    @ddt.ddt
    class MyTest(unittest.TestCase):
    
        @classmethod
        def setUpClass(cls):
            print "SetUp"
            time.sleep(2)
    
        @classmethod
        def tearDownClass(cls):
            print "teardown"
            time.sleep(2)
    
        @ddt.data(*info)
        def test01(self, mes):
            print mes
    
        @ddt.data(*info)
        def test03(self, res):
            print res["username"]
    
        def test02(self):
            print "test02"
    
    if __name__ == '__main__':
        unittest.main()
    

    运行上面代码:

        可以看到,我们的info是一个列表,里面套了两个字典,在打印res["username"]的时候回将两个username都打印出来;这也是数据驱动的好处,也就是将用到的数据放到一起(比如一个Excel中),然后通过数据驱动就可以读到Excel中的所有数据了。

        以上内容就是我要讲的所有的unittest需要了解的知识了,其实东西并不多,unittest模块常用的基本上就这三篇的知识,将来无论你做接口测试还是UI自动化,都会用到以上知识,所以,现在就学会了记住了,将来会少走很多弯路~~

    欢迎大家关注微信公众号“自动化测试实战”,我们一起进步!

  • 相关阅读:
    BZOJ2243: [SDOI2011]染色
    BZOJ1036: [ZJOI2008]树的统计Count
    转自 x_x_的百度空间 搞ACM的你伤不起
    wcf test client
    wcf test client
    log4net编译后命名空间找不到的问题
    log4net编译后命名空间找不到的问题
    Hive Getting Started
    Hive Getting Started
    刚听完CSDN总裁蒋涛先生的学术报告
  • 原文地址:https://www.cnblogs.com/captainmeng/p/7722346.html
Copyright © 2011-2022 走看看