Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Python unittest – assertTrue() function

  • Last Updated : 30 Oct, 2020

assertTrue() in Python is a unittest library function that is used in unit testing to compare test value with true. This function will take two parameters as input and return a boolean value depending upon the assert condition. If test value is true then assertTrue() will return true else return false.

Syntax: assertTrue(testValue, message)
 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

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.

Listed below are two different examples illustrating the positive and negative test case for given assert function:

Example 1: Negative Test case

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()

Output:

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)






Example 2: Positive Test case

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()

Output:

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

OK






Reference: https://docs.python.org/3/library/unittest.html




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!