Tuesday, July 14, 2009

How do I write a program to test my Rational Numbers Class in C++?

C++ Programing

How do I write a program to test my Rational Numbers Class in C++?
The best way I have found to test any class is using assert statements. Example:





Say you wrote a vector class and you wanted to test it ( I am just doing this because I dont know the methods you are using in your class).





If you do not know what assert statements are, basically you put an expression in them, or a function that returns a bool. If false is returned your program will stop, and tell you the line that the assertion failed. This is much more useful then having your program output a bunch stuff then having you go through and check it. The assertion will only tell you if somthing is wrong.





#include%26lt;cassert%26gt;


#include%26lt;vector%26gt;








int main(){





std::vector%26lt;int%26gt; v;


assert(v.empty());





v.push(2);


assert(!(v.empty()); // you can also use the not operator


assert(v[0] == 2);


assert(v.front() == 2);





v.push_back(5);





assert(v.back() == 5);


assert(v.size() == 2);





return 0;


};





Test programs structured like this are also very useful if you are not going to be the user of your class. Meaning you could show this to whoever is using your class, and they will understand its capabilities very fast through your examples of how it preforms





You can do this for all your methods, and a few scenarios for each method. Also you may want to write a method to check special cases when you would need access to the private data members, however if you do this make sure you take them out before you release your class.
Reply:Usually I write a member function for the class I am trying to test that calls all of the other functions in the class and makes sure that they return the values I expect them to. The objective is to ensure you hit every "boundary", which are basically numbers or cases where your function is most likely to break.





That way, if you modify a member function later, and you inadvertently break it, your test function will start returning false.


No comments:

Post a Comment