Since I began programming I never though that testing could be an important part of the development process. Now that I’m close to graduate and I’m even working in the test area, I recognize that it is one of the most important parts. But, why do we continue careless about testing? Or is it just looseness?
I think that one of the reasons is that we just want to finish the program and expect that everything works fine, but certainly this never happens. I don’t really remember a program that was perfect since the beginning, and the person who tells you that these programs exist, is a liar.
For this post I will go to the first programming language that I learned (Python), and show you a simple way to start testing your software with a simple tool often called PyUnit.
The Python Unit Testing framework or PyUnit, is a Python version of the known JUnit for Java, and it’s very simple to implement a testing program just by importing the “unittest” framework. (You can follow the next steps below and even get my code from here)
After that we need to import the program that we want to test. For example, if our program is called hello.py, on our test program we will put “import hello”.
After importing both, we need to create some test cases, but in order to create them, we need to create a test class, inheriting from “unittest.TestCase”. The next step is just to add as many test cases as we want. This time, I’m making two: one for the sayHello method and the other for the add method.
In each test case, I will use a function called “assertEqual”. This function lets me compare the result of the hello.py program, to the one I desire. So if I do everything correctly, both tests should pass, otherwise a failure will be displayed.
Last, we need to add the next lines at the bottom of our code, in order to run the test directly from our console:
After that we just run our program as a normal Python one, with “python test_hello.py”
For the demo, I made my test fail, saying that 10 + 5 = 3 (which is false). And that will give us this failure:
This screen says that our test program ran two tests, the first one was successful (represented by the dot), but the second one failed (represented by the F) because 15 != 3.
If we actually run the test case correctly, then something like this will appear on your console.
So that’s how PyUnit works. As you can see, it is very simple to test our programs. I know that this one was very simple, but if we actually create a habit for testing software, then our documentation will be better, we won’t have to worry about failures and we will be certain that everything works fine in our software.
For more information about PyUnit go to this page.
And if you want to see the complete code, go to my repository at GitHub.