Python – Writing Unit Tests with unittest library – Video

In the previous article for abstraction and inheritance I wrote some classes, showing the basics of these two programming concepts. In this one, I will write unit tests for one of the classes, written before.

Software testing is an important part of the software creation process. (This is a fantastic sentence, being able to create such means tha finally all these year of MBA studies have paid off 🙂) Without being tested, you cannot be completely sure that the software runs as expected. Even with testing and full code coverage you still cannot be sure that it is ok. But, testing is good, to give you some average security that the software you have written works as expected. Thus, once you decide to change it, you will not lose sleep, asking yourself the question – “Would it run again?” – but you will simply run the old tests and make sure that it works. Or fix the code up to the moment, when these tests are passing correctly.

If you have never used unit tests, probably you would consider them useless. And you will never think of them as of something good, up to the moment, when a well-written unittest saves you from deploying “broken” code. Then, probably you would understand the importance of those and you would rethink your values in life. Honestly, seeing a broken unittest after a change in the code, due to maintenance is like your old you (or the person who wrote the unittest) is giving you a high-five from the past. And the feeling is nice 🙂

Ok, now about the video and what I wrote there. Pretty much, I tested the class Book, with quite a few methods. There could be more tests to be written, still I wrote quite enough for a 30 minute video. The code below is, also available in GitHub here.

There are quite  a few interesting methods, that I would like to point out separately:

  • setUp – it executes itself before each test
  • tearDown – it executes itself after each test, a bit useless in the current example, but can be quite important in general
  • test_adding_string_for_change_price – it checks for TypeError  and its message.

Yup, this is all!

Thank you for reading so far! 🙂

 

Tagged with: , , , , , ,