Python 测试入门
Alexander Levin
Data Scientist
.setUp():在实际测试前准备测试夹具.tearDown():在测试后清理环境import unittest
class TestLi(unittest.TestCase):
# Fixture setup method
def setUp(self):
self.li = [i for i in range(100)]
# Fixture teardown method
def tearDown(self):
self.li.clear()
# Test method
def test_your_list(self):
self.assertIn(99, self.li)
self.assertNotIn(100, self.li)
正确写法:setUp 的 U 大写,tearDown 的 D 大写。
class TestLi(unittest.TestCase):
# Fixture setup method
def setUp(self):
self.li = [i for i in range(100)]
# Fixture teardown method
def tearDown(self):
self.li.clear()
命令:python3 -m unittest test_in_list.py
包含 .setUp() 和 .tearDown() 的运行输出:

使用 .set_up() 运行的输出:

.setUp() 方法.tearDown() 方法.setUp():在测试前准备夹具.tearDown():在测试后清理环境Python 测试入门