Tips for writing a test program (Ruby / Python / Java)
Archive - Originally posted on "The Horse's Mouth" - 2010-01-29 18:13:44 - Graham Ellis
Where does my test code go?
If you've written a class - a series of methods to be used within another application - how do you test it? How about writing a test program within the same file which runs as the main program if you run your class on its own from the command line, but is ignored if you import / require your class from a higher level application.
In Ruby write your test code within the following condition:
if __FILE__ == %body%
In Python, the condition should be written as follows:
if __name__ == "__main__":
And in Java, you can provide a main method in the class.
public static void main (String [] args) {
What goes in my test code?
I suggest that you create at least TWO instances of an object of the type that the class(es) in the file implement, putting fixed values for demonstration purposed in the file if you can so that the test isn't reliant on external data.
Put unique values into each object to that they can clearly seen to be different, and avoid "1"s which won't cause any change if you multiply by them, also avoid 0s, and giving sequences like 1,2,3,4,5 which won't flag up any errors if you use an index number rather than a value by mistake anywhere.
Having created two objects, use a service of methods to set and get attributes, building in tests of the functionality that your users need, and allowing you the chance to see what the interface to your code's going to look like from a user's viewpoint - in fact it's a good idea to write the tst code early.
Some languages have assert statments or whole test harness structures to let you write code which validates its own responses; use them as appropriate. In other cases, print out the results and also say what the results should be so that the tester / user KNOWS whether it has worked, and obviously, from running it.
What does the test code provide
A piece of code for YOU to test your class is functioning and complete when you have written it
A piece of code for you to test that you class is still functioning when you have modified it
A piece of code that lets your users check that your code is working AND that all dependencies have been met when they install or update it
A piece of code that helps you specify the API to your class
A piece of code that illustrates to your users how they may / should call the API that you have provided ... if you do it well / comment it well, it can form a basis of your documentation.
Examples
There is an example of a test harness in Ruby [here] (and that example, which shows you how the main OO features are implemented in Ruby is more fully dosumented [here].