0
点赞
收藏
分享

微信扫一扫

Python编程:使用unittest模块进行单元测试


单元测试用例代码实例

# -*- coding: utf-8 -*-

# @Date : 2018-12-21
# @Author : Peng Shiyu

import unittest


# 继承unittest.TestCase
class MyTest(unittest.TestCase):
# 必须使用@classmethod 装饰器,所有test运行前运行一次
@classmethod
def setUpClass(cls):
print("类测试开始...")

# 必须使用 @ classmethod装饰器, 所有test运行完后运行一次
@classmethod
def tearDownClass(cls):
print("类测试结束")

# 每个测试用例执行之前做操作
def setUp(self):
print("方法测试开始...")

# 每个测试用例执行之后做操作
def tearDown(self):
print("方法测试结束")

# 测试用例
def test_print(self):
print("测试输出")

# 测试用例
def test_equal(self):
print("测试相等")
self.assertEqual("a", "a")


if __name__ == '__main__':
# 运行所有的测试用例
unittest.main()

"""
类测试开始...方法测试开始...
测试相等
方法测试结束
方法测试开始...
测试输出
方法测试结束
类测试结束
"""

TestCase 中最常用的断言方法

断言方法

检查条件

assertEqual(a, b)

a == b

assertNotEqual(a, b)

a != b

assertTrue(x)

bool(x) is True

assertFalse(x)

bool(x) is False

assertIs(a, b)

a is b

assertIsNot(a, b)

a is not b

assertIsNone(x)

x is None

assertIsNotNone(x)

x is not None

assertIn(a, b)

a in b

assertNotIn(a, b)

a not in b

assertlsInstance(a, b)

isinstance(a, b)

assertNotIsInstance(a, b)

not isinstance(a, b)

运行测试

1、 运行当前源文件中的所有测试用例

unittest.main()

2、运行测试文件

python -m unittest 测试文件

3、运行当前目录下的所有测试用例

python -m unittest

此处可能出现如下字符:

.:代表测试通过

F:代表测试失败 failure

E:代表测试出错 error

s:代表跳过该测试 skip


参考
​​Python单元测试unittest​​




举报

相关推荐

0 条评论