python unittest 单元测试
创建文件sum.py
#! /usr/bin/python3
# -*- encoding: utf-8 -*-
def sum(list):
res = 0
for item in list:
res += item
return res
if __name__ == '__main__':
pass
创建文件test.py
#! /usr/bin/python3
# -*- encoding: utf-8 -*-
import sum
import unittest
class testSum(unittest.TestCase):
def test_sum_case1(self):
self.assertEqual(sum.sum([1, 2, 3]), 6, 'should be 6')
def test_sum_case2(self):
self.assertEqual(sum.sum((1, 2, 3)), 6, 'should be 6')
def test_sum_case3(self):
self.assertNotEqual(sum.sum((-1, 3, 4)), 5, 'should not be 5')
class testOther(unittest.TestCase):
def test_other(self):
self.assertGreater(6, 5, "should be True")
if __name__ == '__main__':
unittest.main()
将以上两个文件放在同级目录中,进入此目录,执行python -m unittest -v 即可自动执行测试
或者需要指定运行某个测试模块,就在-v 后面加上test.py或者其它。