当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。