unittest框架的使用

unittest斷言方法的使用

unittest框架的TestCase類提供以下方法用於測試結果的判斷

方法 檢查 版本
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 3.1
assertIsNot(a, b) a is not b 3.1
assertIsNone(x) x is None 3.1
assertIsNotNone(x) x is not None 3.1
assertIn(a, b) a in b 3.1
assertNotIn(a, b) a not in b 3.1
assertIsInstance(a, b) isinstance(a,b) 3.1
assertNotIsInstance(a, b) not isinstance(a,b) 3.1

 

-assertEqual(first,second,msg=None)

斷言第一個參數和第二個參數是否相等,如果不相等則測試失敗

-assertNotEqual(first,second,msg=None)

assertNotEqueal()和assertEqual()相反,它用於第一個參數與第二個參數是否不相等,如果相等則測試失敗

-assertTrue(expr,msg=None)

-assertFalse(expr,msg=None)

測試表達式是true(或false)

-assertIn(first,second,msg=None)

-assertNotIn(first,second,msg=None)

判斷第一個參數是否在第二個參數中,反過來講,第二個參數是否包含第一個參數

-assertIs(first,second,msg=None)

-assertIsNot(first,second,msg=None)

斷言第一個參數和第二個參數是否爲同一個對象

-assertIsNone(first,second,msg=None)

-assertIsNotNone(first,second,msg=None)

斷言表達式是否爲None對象

-assertIsInstance(first,second,msg=None)

-assertIsNotInstance(first,second,msg=None)

斷言obj是否爲cls的一個實例

實際例子

from calculator import Math
import unittest


class TestMath(unittest.TestCase):

    def setUp(self):
        print("test start")

    def test_add(self):
        j = Math(5,10)
        self.assertEquals(j.add(),15)
        # self.assertEquals(j.add(),12)

    def test_add1(self):
        j = Math(55,100)
        self.assertNotEqual(j.add(),145)

    def test_add2(self):
        j = Math(5,10)
        self.assertTrue(j.add() > 10)

    def assertIs_test(self):
        self.assertIs("abc","abc")
        # self.assertIs("ab","abc")

    def assertIn_test(self):
        self.assertIn("python","hello python")
        # self.assertIn("abc","hello python")

    def tearDown(self):
        print("test end")

if __name__ == '__main__':
    # unittest.main()
    # 構造測試集
    suit = unittest.TestSuite()
    suit.addTest(TestMath("test_case"))
    # 執行測試
    runner = unittest.TextTestRunner()
    runner.run(suit)

 

 

 

 

 

 

 

 

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章