Unit Testing is a one of the best practice that should be performed starting from the first stages and throughout the whole process of development. Unit tests are written to detect bugs early in the development of the application when bugs are less frequent and less expensive to fix.
In this playground I’ll cover the basics of how to create and run a simple test using unittest.
The source code is on GitHub, please feel free to come up with proposals to improve it.
Creating a simple test:
Supposing that we have a very simple add function which return the sum of two integer.
To create a unit test, we have to:
- Create a class derived from unittest.TestCase
- Create a function that start with "test"
In the second example we will check if the result of 3 + 4 equals 8
In these two example we used assertEqual() function to check for an expected result.
unittest provide others functions such as:
- assertTrue() or assertFalse() to verify a condition
- assertRaises() to verify that a specific exception gets raised.
- setUp() and tearDown() methods to define instructions that will be executed before and after each test method
Using assertTrue and assertIn
When a setUp() method is defined, the test runner will run that method prior to each test.
Test discovery is used when you have many test files in that case It would be annoying to have to run each test file separately.
Supposing that you have all your test files in a "tests" directory. To run all of the unittests, use python -m unittest discover tests