當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python unittest assertIsInstance()用法及代碼示例

assertIsInstancePython中的()是單元測試庫函數,用於單元測試中以檢查對象是否為給定類的實例。此函數將使用三個參數作為輸入,並根據斷言條件返回布爾值。如果對象是給定類的實例,它將返回true,否則返回false。

用法: assertIsInstance(object, className, message)

參數assertIsInstance()接受以下說明的三個參數:

  • object:作為給定類的實例檢查的對象
  • className:對象實例要比較的類名
  • message:作為測試消息失敗時顯示的消息的字符串語句。

下麵列出了兩個不同的示例,它們說明了給定assert函數的正麵和負麵測試案例:

示例1:否定測試用例



Python3

# test suite 
import unittest 
  
# test class 
  
  
class Myclass:
    x = 5
  
  
class Myclass2:
    x = 6
  
  
class TestClass(unittest.TestCase):
    # test function to test whether obj is instance of class 
    def test_negative(self):
        objectName = Myclass() 
        # error message in case if test case got failed 
        message = "given object is not instance of Myclass."
        # assertIsInstance() to check if obj is instance of class 
        self.assertIsInstance(objectName, Myclass2, message) 
  
  
if __name__ == '__main__':
    unittest.main()

輸出:

F
======================================================================
FAIL:test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/a2e9f97d79f7d8c1fbd00c4df704d402.py", line 22, in test_negative
    self.assertIsInstance(objectName, Myclass2, message)
AssertionError:<__main__.Myclass object at 0x7f1e9bead0b8> is not an instance of <class '__main__.Myclass2'>:given object is not instance of Myclass.

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (failures=1)

示例2:正測試用例

Python3

# test suite 
import unittest 
  
# test class 
class Myclass:
    x = 5
  
  
class TestClass(unittest.TestCase):
    # test function to test whether obj is instance of class 
    def test_positive(self):
        objectName = Myclass() 
        # error message in case if test case got failed 
        message = "given object is not instance of Myclass."
        # assertIsInstance() to check if obj is instance of class 
        self.assertIsInstance(objectName, Myclass, message) 
  
  
if __name__ == '__main__':
    unittest.main()

輸出:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

參考:https://docs.python.org/3/library/unittest.html




相關用法


注:本文由純淨天空篩選整理自Shivam.Pradhan大神的英文原創作品 Python unittest – assertIsInstance() function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。