python 单元测试

import unittest

def add(a, b):
    return a + b

def minus(a, b):
    return a - b




class TestMath(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print("do something before test only once")

    @classmethod
    def tearDownClass(cls):
        print("do something after test only once")

    def setUp(self):
        print("do something before test")
    def tearDown(self):
        print("do something after test")

    def test_add(self):
        self.assertEqual(3, add(1,2))
    def test_minus(self):
        self.assertEqual(4, minus(5,1))


if __name__ == "__main__":
    # unittest.main(verbosity = 2)

    suite = unittest.TestSuite()

    tests = [TestMath("test_add"), TestMath("test_minus")]
    suite.addTests(tests)

    runner = unittest.TextTestRunner(verbosity=2)
    runner.run(suite)
 

1.引入 unittest

2. 继承unitst.TestCase

3. setUpClass 和 tearDownClass在测试前和测试后做一些想要的工作,只做一次,setUp和tearDown,每个都会执行

4.测试方法用test_开头

5.最常用的是assertEqual这种断言是否相同

6.用unittest.main()来运行

7.还有如果要调整测试次序,要用到TestSuite

8.python -m unittest testunit.py 还可以这样运行测试

 

 

;