unittest 學習
unittest 框架是python的測試框架。脫胎于java的測試框架
-
test case
一個test case的實例,就是一個測試用例。包括了完整的測試流程。setUp() run() tearDown() 分別代表的含義是: 環(huán)境搭建,執(zhí)行測試代碼,測試后的環(huán)境還原
-
test Loader
是用來加載TestCase到TestSuite ,就是從各地尋找test case 創(chuàng)建他們的實例
-
Text Test Runner
Text test runner 是用來執(zhí)行測試用例的,包括運行了多少測試用例,成功了多少,失敗了多少的信息
-
test fixture
fixture 可被認為是測試環(huán)境
所以unittest的整個流程首先寫好,testCase,然后由loader加載case到suite里面,最后再來執(zhí)行
-
官網(wǎng)測試的demo
import unittest class TestStringMethods(unittest.TestCase): def test_upper(self): self.assertEqual('foo'.upper(), 'FOO') def test_isupper(self): self.assertTrue('FOO'.isupper()) self.assertFalse('Foo'.isupper()) def test_split(self): s = 'hello world' self.assertEqual(s.split(), ['hello', 'world']) # check that s.split fails when the separator is not a string with self.assertRaises(TypeError): s.split(2) if __name__ == '__main__': unittest.main()執(zhí)行main 函數(shù),收集函數(shù)名含有'test*'的通配符,但是函數(shù)執(zhí)行順序默認根據(jù)acsll碼來執(zhí)行和加載測試用例??梢宰约簶?gòu)造測試集,來進行測試的順序
-
TestCase 最常用的斷言方法
斷言方法 檢查條件 assertEqaual(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 assertNot(a, b) a is not b assertNone(x) x is None 等方法,來進行對對象的斷言測試,其他方法可以查看unittestg文檔-testcase