Python单元测试-Unittest

Posted SummerStone

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python单元测试-Unittest相关的知识,希望对你有一定的参考价值。

如何在测试代码中跳过测试方法。

在实际的项目中有时需要对一些测试方法进行过滤或者管理。因为并不是每次测试都需要执行所有的测试方法,避免无用功。比如有些测试方法是和操作系统关联的,当然对于用户来说,不希望期望在windows执行的测试,在Linux操作系统也执行,这是说不通的。Unittest刚好也提供了对测试方法进行过滤筛查的功能。

以一个实际案例来说明,直接创建一个测试代码test_code.py,代码如下。

import unittest,sys


class TheTestCase(unittest.TestCase):


@unittest.skip("单元测试跳过这个方法")
def test_nothing(self):
self.fail("此方法测试不会被执行。")

@unittest.skipIf(5 > 3, "此方法不会被执行,由于条件不满足。")
def test_with_condition(self):
pass


@unittest.skipUnless(sys.platform.startswith("dar"),"需要在macOS上运行这个方法。")
def test_on_macOS(self):
pass


if __name__ == __main__:
unittest.main()

其中"unittest.skip"这个功能是直接跳过当前方法的执行,是没有任何附加条件的。

"unittest.skipIf"是带有条件的跳过方法执行,如果满足条件则跳过方法的执行。反之,测试方法会被执行。

"unittest.skipUnless",它是满足条件,则测试方法会被执行;反之会跳过方法。

综上执行,如果在macOS上执行上述测试脚本,会发现test_on_macOS方法会被执行,其他方法都会被跳过。执行结果如下。

Python单元测试-Unittest(五)_Python


如何在测试代码中跳过测试类

和测试方法类似,测试类也可以被跳过执行。细节代码如下,测试类"TheTestCase2"内包含的所有测试方法都会被忽略。

import unittest,sys


class TheTestCase(unittest.TestCase):


@unittest.skip("单元测试跳过这个方法")
def test_nothing(self):
self.fail("此方法测试不会被执行。")

@unittest.skipIf(5 > 3, "此方法不会被执行,由于条件不满足。")
def test_with_condition(self):
pass


@unittest.skipUnless(sys.platform.startswith("dar"),"需要在macOS上运行这个方法。")
def test_on_macOS(self):
pass




@unittest.skip("此测试类将被跳过执行")
class TheTestCase2(unittest.TestCase):


def test_method1(self):
pass


def test_method2(self):
pass


if __name__ == __main__:
unittest.main()

测试结果如下。

Python单元测试-Unittest(五)_Python_02

如果去掉测试类的skip装饰符,那么执行结果如下。

Python单元测试-Unittest(五)_单元测试_03

如果大家想掌握第一手的资讯更新,请关注公众号“测试DAO”。

以上是关于Python单元测试-Unittest的主要内容,如果未能解决你的问题,请参考以下文章

python_unittest_单元测试

python单元测试之unittest

Python单元测试之unittest

python单元测试-unittest

Python单元测试unittest测试框架

python - unittest - 单元测试