What is unit testing?
When doing unit testing, you break your codes into small units (mostly functions), and test if each unit works as expected. Generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function.
Unit testing framework in Python
Let’s say I write a simple math library called Math.
Then I write another file called test_math.py for unit testing.
For creating test cases, we need to define our own class by subclassing unittest.TestCase.
The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. So in our MathTest class, before each test method, a self.math will be created and after the excution of the test method, the tearDown method will be called. If you donnot have a class to test, you may drop the setUp() and tearDown() methods and simply run test methods.
The test method must start with test_.
Now run the test file in terminal.
We can see that the three tests are ran and passed!
The TestCase class provides several assert methods to check for and report failures. The following table lists the most commonly used methods.
Method | Checks that |
---|---|
assertEqual(a, b) | a == b |
assertNotEqual(a, b) | a != b |
assertTrue(x) | bool(x) is True |
assertFalse(x) | bool(x) is False |
assertIs(a, b) | a is b |
assertIsNot(a, b) | a is not b |
assertIsNone(x) | x is None |
assertIsNotNone(x) | x is not None |
assertIn(a, b) | a in b |
assertNotIn(a, b) | a not in b |
assertIsInstance(a, b) | isinstance(a, b) |
assertNotIsInstance(a, b) | not isinstance(a, b) |
When should you perform unit testing?
As often as possible.
Test every function you write in the development process.