Test fixture分三类
- setUp/tearDown
- setUpClass/tearDownClass
- setUpModule/tearDownModule
setUp/tearDown
函数级,分别在函数的开始和结束进行。单个测试用例
```python用例级别(函数)的测试案例
import unittest
class MyClass(unittest.TestCase):
def setUp(self):
print("====> start class")
def tearDown(self):
print("===> end class")
def test_case(self):
print("---->test case")
if name == ‘main‘: unittest.main()
![image.png](https://cdn.nlark.com/yuque/0/2021/png/12405790/1630598507372-fab67452-c5a5-44e8-970d-6ef042bf2dab.png#clientId=u0d00ed0a-b184-4&from=paste&height=223&id=ua3fe66ea&margin=%5Bobject%20Object%5D&name=image.png&originHeight=446&originWidth=1285&originalType=binary&ratio=1&size=42338&status=done&style=none&taskId=u754a049f-c9b2-4b5a-a2f4-e72d80c1be7&width=642.5)<br />可以看到各个函数执行的先后顺序。
- [x] setUp
- [x] test_
- [x] tearDown
<a name="aMwdJ"></a>
## 多个测试用例1
```python
# 全正确的用例
import unittest
class MyClass(unittest.TestCase):
def setUp(self):
print("====> start class")
def tearDown(self):
print("===> end class")
def test_case2(self):
print("---->test case2")
self.assertEqual(4, 4)
def test_case(self):
print("---->test case")
if __name__ == '__main__':
unittest.main()
多个测试用例2
# 有错误的用例
import unittest
class MyClass(unittest.TestCase):
def setUp(self):
print("====> start class")
def tearDown(self):
print("===> end class")
def test_case2(self):
print("---->test case2")
self.assertEqual(3, 4)
def test_case(self):
print("---->test case")
if __name__ == '__main__':
unittest.main()
setUpClass/tearDownClass
类级别,分别在类的开始和结束执行。
import unittest
class MyClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("====> start class")
@classmethod
def tearDownClass(cls):
print("===> end class")
def setUp(self):
print("start test")
def tearDown(self):
print("end test")
def test_case(self):
print("---->test case")
self.assertEqual(2 + 2, 4)
def test_case2(self):
print("---->test case2")
self.assertEqual(4, 4)
if __name__ == '__main__':
unittest.main()
setUpModule/tearDownModule
文件级别,分别在文件的开始和结束执行。
import unittest
def setUpModule():
print(">>>>>>>>>>>>>> start module")
def tearDownModule():
print(">>>>>>>>>>>>>> start module")
class MyClass(unittest.TestCase):
@classmethod
def setUpClass(cls):
print("====> start class")
@classmethod
def tearDownClass(cls):
print("===> end class")
def setUp(self):
print("start test")
def tearDown(self):
print("end test")
def test_case(self):
print("---->test case")
self.assertEqual(2 + 2, 4)
def test_case2(self):
print("---->test case2")
self.assertEqual(4, 4)
if __name__ == '__main__':
unittest.main()