Whenever we use unittest, there are some methods we use in our script. These methods are the following:
- assertEqual() and assertNotEqual(): This checks for an expected result
- assertTrue() and assertFalse(): This verifies a condition
- assertRaises(): This verifies that a specific exception gets raised
- setUp() and tearDown(): This defines instructions that are executed before and after each test method
You can use the unittest module from the command line as well. So, you can run the previous test script as follows:
student@ubuntu:~$ python3 -m unittest test_addition.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK
Now, we will see another example. We will create two scripts: if_example.py and test_if.py. if_example.py will be our normal script and test_if.py will contain test case. In this test, we are checking whether the entered number is equal to 100 or not. If it is equal to 100 then our test will be successful. If not, it must show a FAILED result.
Create a if_example.py script and write the following code in it:
def check_if():
a = int(input("Enter a number \n"))
if (a == 100):
print("a is equal to 100")
else:
print("a is not equal to 100")
return a
Now, create a test_if.py test script and write following code in it:
import if_example
import unittest
class Test_if(unittest.TestCase):
def test_if(self):
result = if_example.check_if()
self.assertEqual(result, 100)
if __name__ == '__main__':
unittest.main()
Run the test script as follows:
student@ubuntu:~/Desktop$ python3 -m unittest test_if.py
Enter a number
100
a is equal to 100
.
----------------------------------------------------------------------
Ran 1 test in 1.912s
OK
We run the script for a successful test result. Now, we will enter some value other than 100 and we must get a FAILED result. Run the script as follows:
student@ubuntu:~/Desktop$ python3 -m unittest test_if.py
Enter a number
50
a is not equal to 100
F
======================================================================
FAIL: test_if (test_if.Test_if)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/home/student/Desktop/test_if.py", line 7, in test_if
self.assertEqual(result, 100)
AssertionError: 50 != 100
----------------------------------------------------------------------
Ran 1 test in 1.521s
FAILED (failures=1)