Python 单元测试

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Python 单元测试脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Python UnITtest

Unit test

python 有个模块叫做 unittes,是Junit的Python实现,一个常用的单元测试框架。

文件结构

我一般是把UnitTest目录和src目录平行放置。
下面是Python官方文档给出的例子:

import unittest

class TestStringMethods(unittest.TestCase):

    def test_upPEr(self):
        self.assertEqual('foo'.upper(), 'FOO')

    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)
            

如果要运行unittest,只需要加上

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

然后直接运行该脚本。

每个test case的名字都由test开头,个人习惯在test和下划线之间加上test case的序号。

  • test01_condition1(self)
  • test02_condition1(self)
  • ...

测试环境的搭建与还原

  • SETUP() --- 用于测试环境的构建, 所有test case开始前执行
  • tearDown() --- 测试环境的还原, 所有test case结束后执行

跳过某test case

如果想跳过某test case暂不执行,可以在该method前加一个decorator

@unittest.skip("demonstrating skipping")
def test12_condition12(self):
    self.assertEqual(1, 2)

脚本宝典总结

以上是脚本宝典为你收集整理的Python 单元测试全部内容,希望文章能够帮你解决Python 单元测试所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。