它的使用非常简单,你的测试类必须是unittest.TestCase的子类,然后定义相应的测试函数,只要把函数名称写成testXXX的格式,然后运行unittest.main(),这些测试函数就会被调用.另外,unittest.TestCase提供了一个函数setUp,这个函数会在每个测试函数被调用之前都调用一次,如果需要做一些初始化处理,可以重载这个函数.unittest模块还提供了一些高级功能,可以查看帮助.
1
import unittest
2![]()
3
class Person:
4
def age(self):
5
return 34
6
def name(self):
7
return 'bob'
8
9
class TestSequenceFunctions(unittest.TestCase):
10
11
def setUp(self):
12
self.man = Person()
13
print 'set up now'
14
15![]()
16
def test1(self):
17
self.assertEqual(self.man.age(), 34)
18![]()
19
def test2(self):
20
self.assertEqual(self.man.name(), 'bob')
21![]()
22
def test3(self):
23
self.assertEqual(4+78,23)
24![]()
25
if __name__ == '__main__':
26
unittest.main()
一些相关的链接:
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

- A chapter on Unit Testing in Mark Pilgrim's Dive Into Python.
unittest
module documentation, in the Python Library Reference.- UnitTests on the PortlandPatternRepository Wiki, where all the cool ExtremeProgramming kids hang out.
- Unit Tests in Extreme Programming: A Gentle Introduction.
- Ron Jeffries espouses on the importance of Unit Tests at 100%.
- Ron Jeffries writes about the Unit Test in the Extreme Programming practices of C3.
- PyUnit's homepage.