In this, we are going to understand the unit testing done in Python with some examples to understand it more perfectly.
UNIT TESTING IN PYTHON
Unit testing is done in Python to test the individual units of a program to ensure the work is done as expected by the program. There are many frameworks for unit testing. One of the most commonly used unit test frameworks is “unittest”.
Unit testing helps in understanding the code easily with different aspects of our code in our project.
Steps on how to perform unit testing using ‘unittest’:
- firstly, import the module.
import unittest
- create a subclass for the ‘unittest’:
for example “unittest. testcase” in this way any subclass can be created. - Also, write test methods:
The ‘assert’ method is used for checking the result which we have expected.
various ‘assert’ methods can be used in which we are using
‘assertEqual(a,b)’ — check if ‘a==b’ which helps in checking that both the a and b are equal.
class TestTheFunction(unittest.Testcase): def test_case_1(self): self.assertEqual(the_function(1,2),3)
4. Run the Test :
The code can run by adding this code at of the file:
if __name__ == '__main__': unittest.main()
As an alternative,you can also run the test by using this command line:
python -m unittest test_module.py
For a better understanding, let’s see an example,
The function to be Tested(‘my_module.py’):
def add(a, b): return a + b def subtract(a, b): return a - b
The test file(‘test_my_module.py’):
import unittest from my_module import add, subtract class TestMathFunctions(unittest.TestCase): def test_add(self): self.assertEqual(add(1, 2), 3) self.assertEqual(add(-1, 1), 0) self.assertEqual(add(-1, -1), -2) def test_subtract(self): self.assertEqual(subtract(2, 1), 1) self.assertEqual(subtract(-1, 1), -2) self.assertEqual(subtract(-1, -1), 0) if __name__ == '__main__': unittest.main()
Run The Test:
you can run the test by executing the test file by:
python test_my_module.py
Output:
.. ------------------------------------------------------------------ Ran 2 tests in 0.000s
As our all the test cases are been passed ,we got the output. If any test fails,’unittest’ will provide a detailed report showing which test failed and why,making it easier to debug and fix issues in your code.