问题:
查了一些网上的资料,主要介绍了两种方式:
方式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)
原文:https://www.cnblogs.com/We612/p/12759862.html