Automated unit testing has been around for more than a decade now. I remember back in 2008, a colleague introduced to our team the concept of MVP pattern and in the process the advantage of using the pattern in unit testing. The concept of automated testing using NUnit and mocking using NMock was also discussed. That is where I began to see the advantage of implementing Test Driven Development methodology to developers. Unfortunately, the company where I moved don't see it as such. Thus, I was only able to practice it on my learning time. With the recent events in my life , I now have more time exploring this concept a little further. A series of post will concentrate on this concept using Python and C#. Lets begin with Python.
Lets begin with simple unit test using unittest. For the code samples, we will use the following directory structure :
I organized my codes in such a way that the actual application code is separated from the unit test codes. For this to work unit test discovery will be used if you are to run it on the terminal. In my case, I run the tests inside PyCharm.
To make this as simple as possible, I will use a simple Calculator application with the following methods to be tested :
- add(num1, num2) - Add two numbers
- subtract(num1,num2) - Subtraction
- multiply(num1,num2) - Multiplication
- divide(num1,num2) - Division
The Unit Test
If you are accustomed on creating unit test in .Net, the names of the test file as well as test methods are insignificant . Aside from the general rules in naming files and method names, theres nothing special to be considered. In Python, however, its more strict. Below are the two rules that are significant for the tests to be discovered:
- The file name of the test file should start with "test: (i.e. test_calculator.py)
- The method names should start with test ( i.e. test_add)
Since we are using unittest, all test classes should inherit from unittest.TestCase. For the example, the assertEqual is used. Complete documentation on Python 3 regarding unittest can be found in this link.
Running the Test
To run the script, we can use the terminal or command prompt to run discovered unit test using the following command :
Running test in the command line / terminal is far less aesthetically appealing that its Visual Studio equivalent but some Python editors such as PyCharm can provide such experience too.