Python unittest – assertIsInstance()函数
Python中的assertIsInstance () 是一个 unittest 库函数,用于在单元测试中检查对象是否是给定类的实例。该函数将三个参数作为输入,并根据断言条件返回一个布尔值。如果对象是给定类的实例,它将返回 true,否则返回 false。
Syntax: assertIsInstance(object, className, message)
Parameters: assertIsInstance() accept three parameters which are listed below with explanation:
- object: Object which is checked as an instance of the given class
- className: Class name to be compared for object instance
- message: a string sentence as a message which got displayed when the test case got failed.
下面列出了两个不同的示例,说明了给定断言函数的正负测试用例:
示例 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()
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()
输出:
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 : 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