test case是单元测试中的最小个体。它检查特定输入的响应信息。unittest提供了一个基础类:TestCase,用来创建test case。 test suite是test case的合集,通常用test suite将test case汇总然后一起执行。 test runner是一个执行器,它可以执行case并提供结果给用户。它可以提供图形界面、文本界面或者返回一个值表示测试结果。 1、unittest官方文档:中文https://blog.csdn.net/ljl6158999/article/details/80994979 2、用法:
!/usr/bin/python
import unittest
class TestStringMethods(unittest.TestCase):
代码语言:javascript复制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)
if name == 'main': unittest.main()
''' 套件使用:
def suite(): suite = unittest.TestSuite() suite.addTest(WidgetTestCase('test_default_widget_size')) suite.addTest(WidgetTestCase('test_widget_resize')) return suite
if name == 'main': runner = unittest.TextTestRunner() runner.run(suite() '''
''' 跳过失败:
class MyTestCase(unittest.TestCase):
代码语言:javascript复制@unittest.skip("demonstrating skipping")
def test_nothing(self):
self.fail("shouldn't happen")
@unittest.skipIf(mylib.__version__ < (1, 3),
"not supported in this library version")
def test_format(self):
# Tests that work for only a certain version of the library.
pass
@unittest.skipUnless(sys.platform.startswith("win"), "requires Windows")
def test_windows_support(self):
# windows specific testing code
pass
'''
''' 测试开头只执行一次和测试结束后只执行一次的方法: @classmethod def setUpClass(cls):
@classmethod def tearDownClass(cls): '''
''' 常用方法: assertEqual assertNotEqual assertTrue assertFalse assertIs assertIsNone assertIsNotNone assertIn assertInstance '''