测试步骤

1. 导入unittest模块

import unittest

2. 编写测试的类继承unittest.TestCase

class Tester(unittest.TestCase)

3. 编写测试的方法必须以test开头

def test_add(self)

def test_sub(self)

4.使用TestCase class提供的方法测试功能点

Method

Checks that

New in

​assertEqual(a, b)​

a == b

 

​assertNotEqual(a, b)​

a != b

 

​assertTrue(x)​

bool(x) is True

 

​assertFalse(x)​

bool(x) is False

 

​assertIs(a, b)​

a is b

2.7

​assertIsNot(a, b)​

a is not b

2.7

​assertIsNone(x)​

x is None

2.7

​assertIsNotNone(x)​

x is not None

2.7

​assertIn(a, b)​

a in b

2.7

​assertNotIn(a, b)​

a not in b

2.7

​assertIsInstance(a, b)​

isinstance(a, b)

2.7

​assertNotIsInstance(a, b)​

not isinstance(a, b)

2.7

5.调用unittest.main()方法运行所有以test开头的方法

if __name__ == '__main__':
unittest.main()

实例如下

被测试类

#!/usr/bin/python
#coding=utf-8

class Computer(object):
@staticmethod
def add(a, b):
return a + b;

@staticmethod
def sub(a, b):
return a - b;<strong> </strong>


测试类

#!/usr/bin/python
#coding=utf-8
import unittest
from Testee import Computer

class Tester(unittest.TestCase):
def test_add(self):
self.assertEqual(Computer.add(2, 3), 5, "test add function")

def test_sub(self):
self.assertEqual(Computer.sub(5, 1), 4, "test sub function")

if __name__ == '__main__':
unittest.main()


运行结果:

----------------------------------------------------------------------

Ran 2 tests in 0.000s

OK