一、测试套件:
1.方式一:unittest.main()
import unittest
class TestDemo(unittest.TestCase):
def setUp(self) -> None:
print("setUp")
def tearDown(self) -> None:
print("teardown")
def test_01(self):
print("test01")
def test_02(self):
print("test02")
def test_03(self):
print("test03")
if __name__ == '__main__':
unittest.main(verbosity=2)
执行结果
2.方式二:unittest.TestSuite()
import unittest
class TestDemo(unittest.TestCase):
def setUp(self) -> None:
print("setUp")
def tearDown(self) -> None:
print("teardown")
def test_01(self):
print("test01")
def test_02(self):
print("test02")
def test_03(self):
print("test03)
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestDemo("test_02"))
suite.addTest(TestDemo("test_01"))
runner = unittest.TextTestRunner(verbosity=2)
runner.run(suite)
执行结果:
3.方式三:unittest.defaultTestLoader()
import unittest
class TestDemo(unittest.TestCase):
def setUp(self) -> None:
print("setUp")
def tearDown(self) -> None:
print("teardown")
def test_01(self):
print("test01")
def test_02(self):
print("test02")
def test_03(self):
print("test03)
if __name__ == '__main__':
test_dir = "./"
discover = unittest.defaultTestLoader.discover(test_dir, pattern='pattern='demo.py')
runner = unittest.TextTestRunner(verbosity=2)
runner.run(discover)
执行结果:
二、结果输出到文件
import unittest
class TestCan(unittest.TestCase):
def test_01(self):
print("hello world1")
def test_02(self):
print("hello world2")
if __name__ == '__main__':
suite = unittest.TestSuite()
suite.addTest(TestCan("test_01"))
suite.addTest(TestCan("test_02"))
with open("res.txt", "a", encoding="utf-8") as file:
runner = unittest.TextTestRunner(stream=file, verbosity=2)
runner.run(suite)
写入结果的文件
|