首页 > 其他 > 详细

unnitest用例按顺序执行方法总结

时间:2020-04-23 13:22:33      阅读:191      评论:0      收藏:0      [点我收藏+]

问题:

  • 我们知道根据排序规则,unittest执行测试用例,默认是根据ASCII码的顺序加载测试用例,数字与字母的顺序为:0-9,A-Z,a-z。我们怎么来控制用例执行的顺序呢?
  • 一个测试文件,我们直接执行该文件即可,但如果有多个测试文件,怎么进行组织,总不能一个个文件执行吧?

查了一些网上的资料,主要介绍了两种方式:
方式1,通过TestSuite类的addTest方法,按顺序加载测试用例:

class TestStringMethods(unittest.TestCase):
    def setUp(self) -> None:
        print(‘hello‘)

    def tearDown(self) -> None:
        print(‘Goodbai‘)

    def test_upper(self):
        self.assertEqual(‘foo‘.upper(), ‘FOO‘, msg="预期结果与实际结果不相等")

    def test_isupper(self):
        self.assertTrue(‘FOO‘.isupper())
        self.assertFalse(‘Foo‘.isupper())

    def test_split(self):
        s = ‘hello world‘
        self.assertEqual(s.split(), [‘hello‘, ‘world‘])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)
if __name__ == ‘__main__‘:
    suite = unittest.TestSuite()
    
    # 一 测试用例模块名直接传入,按照默认排序规则执行用例
    # suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestStringMethods))

    # 二 根据逐个添加的顺序执行
    # suite.addTest(TestStringMethods("test_split"))
    # suite.addTest(TestStringMethods("test_upper"))

    # 三 根据列表的索引顺序执行,我们使用这种方式:便捷
    suite.addTests([TestStringMethods("test_split"), TestStringMethods("test_upper"), TestStringMethods("test_isupper")])
    
    with open(‘UnittestTextReport02.txt‘, ‘a‘) as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        runner.run(suite)

方式2,通过修改函数名的方式:

import unittest
class TestStringMethods(unittest.TestCase):
    def setUp(self) -> None:
        print(‘hello‘)

    def tearDown(self) -> None:
        print(‘Goodbai‘)

    def test_1_upper(self):
        self.assertEqual(‘foo‘.upper(), ‘FOO‘, msg="预期结果与实际结果不相等")

    def test_2_isupper(self):
        self.assertTrue(‘FOO‘.isupper())
        self.assertFalse(‘Foo‘.isupper())

    def test_3_split(self):
        s = ‘hello world‘
        self.assertEqual(s.split(), [‘hello‘, ‘world‘])
        # check that s.split fails when the separator is not a string
        with self.assertRaises(TypeError):
            s.split(2)
if __name__ == ‘__main__‘:
    suite = unittest.TestSuite()
    # 测试用例模块名直接传入 
    suite.addTest(unittest.TestLoader().loadTestsFromTestCase(TestStringMethods))     
    with open(‘UnittestTextReport02.txt‘, ‘a‘) as f:
        runner = unittest.TextTestRunner(stream=f, verbosity=2)
        runner.run(suite)

unnitest用例按顺序执行方法总结

原文:https://www.cnblogs.com/We612/p/12759862.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!