Python unittest – assertTrue()函数
Python中的 assertTrue() 是一个 unittest 库函数,用于在单元测试中将测试值与 true 进行比较。该函数将两个参数作为输入,并根据断言条件返回一个布尔值。如果测试值为真,则 assertTrue() 将返回真,否则返回假。
Syntax: assertTrue(testValue, message)
Parameters: assertTrue() accepts two parameters which are listed below with explanation:
- testValue: variable of boolean type which is used in the comparison by function
- message: a string sentence as a message which got displayed when the test case got failed.
下面列出了两个不同的示例,说明了给定断言函数的正负测试用例:
示例 1:否定测试用例
Python3
# unit test case
import unittest
class TestStringMethods(unittest.TestCase):
# test function
def test_negative(self):
testValue = False
# error message in case if test case got failed
message = "Test value is not true."
# assertTrue() to check true of test value
self.assertTrue( testValue, message)
if __name__ == '__main__':
unittest.main()
Python3
# unit test case
import unittest
class TestStringMethods(unittest.TestCase):
# test function
def test_positive(self):
testValue = True
# error message in case if test case got failed
message = "Test value is not true."
# assertTrue() to check true of test value
self.assertTrue( testValue, message)
if __name__ == '__main__':
unittest.main()
输出:
F
======================================================================
FAIL: test_negative (__main__.TestStringMethods)
----------------------------------------------------------------------
Traceback (most recent call last):
File "p1.py", line 11, in test_negative
self.assertTrue( testValue, message)
AssertionError: False is not true : Test value is not true.
----------------------------------------------------------------------
Ran 1 test in 0.000s
FAILED (failures=1)
示例 2:正面测试用例
Python3
# unit test case
import unittest
class TestStringMethods(unittest.TestCase):
# test function
def test_positive(self):
testValue = True
# error message in case if test case got failed
message = "Test value is not true."
# assertTrue() to check true of test value
self.assertTrue( testValue, message)
if __name__ == '__main__':
unittest.main()
输出:
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK
参考:https://docs。 Python.org/3/library/unittest.html