Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Each test case in its own method

We can put each check in a separate function.

import unittest
import mymath

class TestMath(unittest.TestCase):

    def test_add_2_3(self):
        self.assertEqual(mymath.add(2, 3), 5)

    def test_div_6_3(self):
        self.assertEqual(mymath.div(6, 3), 2)

    def test_div_42_1(self):
        self.assertEqual(mymath.div(42, 1), 42)

    def test_add_1_1(self):
        self.assertEqual(mymath.add(-1, 1), 0)

#if __name__ == '__main__':
#    unittest.main()

In this case the reporting will show 4 tests.

$ python -m unittest test_mymath_with_unittest_separated.py 
....
----------------------------------------------------------------------
Ran 4 tests in 0.000s

OK

The advantage of putting them in separate functions is that then the tests can run independently.