Python provides a powerful testing framework in its unittest
module.
Unit testing is a well-established technique for evaluating the correctness of software components (see testing). Unit testing involves testing individual units of a software system in isolation to determine if they behave as advertised. Examples of individual software units include functions, methods, objects, and modules.
Python’s unittest
module is easy to use.
The following steps explain how to use the unit testing
module for simple testing:
- Import the
unittest
module. - Import the code to test as necessary.
- Derive a class from
unittest.TestCase
-
Add methods for each test to perform.
- Each method’s name must have the prefix test.
- Each method must accept only the
self
parameter. - Add to the method’s body any code required to perform the test.
- Within the method call the assertEqual method to compare a computed value to an expected value.
-
Add the following code to the test program:
if __name__ == '__main__': unittest.main()