Test the mymath module
Unittests are usually written in separate files.
We need to create one or more classes called TestSomething and inherit from unittest.TestCase.
Inside the class there have to be one or more test-methods. Each one must start with test_.
import unittest
import mymath
class TestMath(unittest.TestCase):
def test_match(self):
self.assertEqual(mymath.add(2, 3), 5)
self.assertEqual(mymath.div(6, 3), 2)
self.assertEqual(mymath.div(42, 1), 42)
self.assertEqual(mymath.add(-1, 1), 0)
if __name__ == '__main__':
unittest.main()
$ python test_mymath_with_unittest.py
.
-------------------------------------------------
Ran 1 test in 0.000s
OK
The single . in this output indicates that we had a single test function and it was successful.
Alternatively we can leave out the last two lines:
if __name__ == '__main__':
unittest.main()
And use the unittest itself to run the tests.
python -m unittest test_mymath_with_unittest.py