Chapter 8: Unit testing

Easier unit testing

face Josiah Wang

As your code gets more complex, there will be more tests to be run.

Our previous method of writing multiple test() functions works to a certain extent. But it starts to get a bit hard to manage after a while.

Would it not be great if we can have some easy way to write and organise all our test cases?

Also, remember that with TDD, the idea is to write test cases before you even start implementing the functionality. The goal is to get to a ‘green’ state (no errors) as soon as possible, and then stay there! So, whenever we have refactor our code, we should run all tests to make sure that we are in a ‘green’ state (and correct anything as soon as possible otherwise!)

Therefore, we also need a way to run all tests easily (rather than module by module), without even having to think!

In this chapter, I will give you a quick glimpse on using the unittest module from the Python Standard Library to:

  • make it easier to write test cases
  • automatically run all test cases