自定义类继承自unittest.TestCase , 并在类内部定义以test开头的方法。
在类外面写上这句代码
if __name__ == '__main__':
unittest.main()
就会执行类中所有test开头的方法
# -*- coding:UTF-8 -*-
'''
Created on 2015年10月25日
@author: young
'''
import unittest
class TestDict(unittest.TestCase):
def test_init(self):
print "test_init"
self.assertEquals(1, -1)
def test_key(self):
print "test_key"
# self.assertEquals(d.key, 'value')
def test_attr(self):
print "test_attr"
# self.assertTrue('key' in d)
# self.assertEquals(d['key'], 'value')
def test_keyerror(self):
print "test_keyerror"
#
with self.assertRaises('1/0!!!!!!!!!'):
1/0
def test_attrerror(self):
print "test_attrerror"
#
# with self.assertRaises(AttributeError):
# value = d.empty
#
def testFunn(self):
print "testFunn"
if __name__ == '__main__':
unittest.main()
打印如下
.testFunn
..F.test_attr
test_attrerror
test_init
test_key
test_keyerror
E
======================================================================
ERROR: test_keyerror (__main__.TestDict)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/young/Documents/workspace_python/python1/src/test.py", line 35, in test_keyerror
1/0
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/unittest/case.py", line 117, in __exit__
if not issubclass(exc_type, self.expected):
TypeError: issubclass() arg 2 must be a class or tuple of classes
======================================================================
FAIL: test_init (__main__.TestDict)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/young/Documents/workspace_python/python1/src/test.py", line 17, in test_init
self.assertEquals(1, -1)
AssertionError: 1 != -1
----------------------------------------------------------------------
Ran 6 tests in 0.001s
FAILED (failures=1, errors=1)