Python Unit Tests using unittest (Easy start!)
February 10, 2020 by Jane

After using with GoogleTest for C++, I am moving on to Python. Since python has built-in library for testing, it's basically a no brainer. Therefore I'm using unittest for python

To be honest, I had a much easier experience with unittest than GoogleTest. Perhaps it is because I had used these during my co-op at eBrisk Video or what but it took only about 15 minutes to get it working. So before I forget again, I'm going to write a debrief for my future self.

  1. import unittest on top of all the test files
  2. import whatever modules and auxillary modules that is going to be tested
  3. class <TestThisModule>(unittest.TestCase):  inherit the unittest.TestCase class
  4. def test_<test_case_name>(self): python's unittest has discovery feature that assumes all functions starting with "test" are tests and will be automatically run
  5. In the test functions use self.assertTrue/False/Equal etc to test for the validity of output
  6. if __name == '__main__': unittest.main()  write this at the bottom (the unittest.main() should be on the next line and indented) so the file can be run separately on its own
  7. I suggest using classes to group together tests for the same function and files to group the tests together for the same structure or object, in any case keep things organized so it's easy to see what is being tested and what is expected etc.

Robust coding here I come!